Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child class constructor method in Lua

Having a bit of a hard time to grasp the concept of inheritance (and metatables) in Lua. The official tutorial doesn't specifically explain how to make a constructor for the child class.

The problem with my example is that player:move() is nil, so player is still an Object class

-- Generic class
Object = {}
function Object:new (type,id,name)
    o = {}
    self.type = type or "none"
    self.id = id or 0
    self.name = name or "noname"
    setmetatable(o, self)
    self.__index = self
    return o
end

function Object:place(x,y)
    self.x = x
    self.y = y
end

-- Player class
Player = Object:new()

function Player:new(id,name)
    o = Object:new("player",id,name)
    o.inventory = {}
    o.collisions = {}
    return o
end

function Player:move(x,y)
    return print("moved to " ..x.." x " .. y)
end

local player = Player:new(1, "plyr1")
player:move(2,2)
like image 666
Mojimi Avatar asked Oct 12 '16 17:10

Mojimi


1 Answers

In the constructor Player:new, we are returning an object of Object class through the following line:

o = Object:new("player",id,name)

Once we remove that, player:move() will be called:

moved to 2 x 2

The reason is, even though we are calling the Player:new constructor, we are returning therein actually an instance of Object class. o is in inherited property in this case.

like image 88
Unheilig Avatar answered Oct 02 '22 01:10

Unheilig