Lua 继承和方法

如何从类 actor 继承一个名为 player 的新类,并使方法 actor:new(x, y, s) 在方法 player:new(x, y, s) 中被调用,参数相同。我需要让 player:newactor:new 一样,但是还需要额外的参数,以便 player 拥有比 actor 更多的属性。

是否有一种方法不只在 new 方法中实现这个功能,而是在其他方法中,例如 player:move(x, y) 将调用 actor:move(x, y)self:move(x, y) ,但附加其他代码?

我使用以下模式在模块中创建类:

local actor = {}

function actor:new(x, y, s)

    self.__index = self

    return setmetatable({
        posx = x,
        posy = y,

        sprite = s
    }, self)
end

-- methods

return actor
点赞
用户2858170
用户2858170

一个好的方法是有一个单独的初始化实例的函数。然后你可以在继承的类中简单地调用基类的初始化。

像这个例子:http://lua-users.org/wiki/ObjectOrientationTutorial

function CreateClass(...)
  -- "cls" is the new class
  local cls, bases = {}, {...}
  -- copy base class contents into the new class
  for i, base in ipairs(bases) do
    for k, v in pairs(base) do
      cls[k] = v
    end
  end
  -- set the class's __index, and start filling an "is_a" table that contains this class and all of its bases
  -- so you can do an "instance of" check using my_instance.is_a[MyClass]
  cls.__index, cls.is_a = cls, {[cls] = true}
  for i, base in ipairs(bases) do
    for c in pairs(base.is_a) do
      cls.is_a[c] = true
    end
    cls.is_a[base] = true
  end
  -- the class's __call metamethod
  setmetatable(cls, {__call = function (c, ...)
    local instance = setmetatable({}, c)
    -- run the init method if it's there
    local init = instance._init
    if init then init(instance, ...) end
    return instance
  end})
  -- return the new class table, that's ready to fill with methods
  return cls
end

你可以简单地这样做:

actor = CreateClass()
function actor:_init(x,y,s)
  self.posx = x
  self.posy = y
  self.sprite = s
end

player = CreateClass(actor)
function player:_init(x,y,s,name)
  actor.init(self, x,y,s)
  self.name = name or "John Doe"
end
2021-06-04 05:33:19