Lua中的子类构造函数方法

Moj*_*imi 5 inheritance lua lua-table

很难掌握Lua中的继承(和元表)概念。官方教程没有具体说明如何为子类创建构造函数。

我的示例的问题player:move()nil,因此播放器仍然是Object课程

-- 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)
Run Code Online (Sandbox Code Playgroud)

Unh*_*lig 3

在构造函数中,我们通过以下行Player:new返回类的对象:Object

o = Object:new("player",id,name)
Run Code Online (Sandbox Code Playgroud)

一旦我们删除它,player:move()就会被调用:

moved to 2 x 2
Run Code Online (Sandbox Code Playgroud)

原因是,即使我们调用Player:new构造函数,我们实际上也在其中返回一个Object类的实例。o在这种情况下属于继承财产。