Shadowblitz16
Shadowblitz16

Reputation: 145

classes with inheritance the simplified way?

EDIT I have found a much easier way to do this in lua but the problem is method inheritance

basically the syntax would go like this

Object

object       = {}
object.base  = ?
object.value = 0

function object:create(x, y)
    local copy

    --copy table
    if type(self) == "table" then
        copy = {}  for k, v in pairs(self) do copy[k] = v:create() end
    else
        copy = self
    end

    --set base
    copy.base = self

    --set copy vars
    copy.x = x
    copy.y = y

    return copy
end

function object:update() 
    self.value = self.value + 1
end

Player

player       = object:create()
player.value = 1

function player:create(x, y, size)
    base:create(x, y) --inherit base event
end

--automaticly inherits update event since it is not redeclared

I'm not sure how to go about doing this though

Upvotes: 2

Views: 78

Answers (2)

kingJulian
kingJulian

Reputation: 6170

Inheritance in Lua is basically implemented using metatables. In code:

function object:new (o)
      o = o or {}
      -- Put the rest of your create function code here
      setmetatable(o, self)
      self.__index = self
      return o
    end

function object:update() 
    self.value = self.value + 1
end

Now create an empty Player class that will be a subclass of your base Object class and will inherit all its behavior from it.

Player = Object:new()

Player is now an instance of Object. Instantiate a new Player object, p in order to inherit the new method from Object.

p = Player:new{x=1, y=2, size=3}

This time, however, when new executes, the self parameter will refer to player. Therefore, the metatable of p will be Player, whose value at index __index is also Player. So, p inherits from Player, which inherits from Object.

Now when you'll code:

p:create{x=10, y=20, size=100}

lua won't find a create field in p, so it will look into Player class; it won't find a create field there, too, so it will look into Object and there it will finds the original implementation of create. The same thing will happen with the update function.

Of course Player class can redefine any method inherited from its superclass, Object. So for example you can redefine -if you want- the create function:

function Player:create()
   --New create code for Player
end

Now when you'll call p:create{x=10, y=20, size=190}, Lua will not access the Object class, because it finds the new create function in Player first.

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80629

You are making a reference to base directly, whereas, it is actually an attribute of your player object:

function player:create(x, y, size)
    self.base:create(x, y)
end

Upvotes: 0

Related Questions