Lua 继承和方法

Lua inheritance and methods

如何从 class actor 继承一个新的 class player 并使方法 actor:new(x, y, s) 在方法 player:new(x, y, s) 中调用相同参数。我需要使 player:new 相同但具有附加参数,因此 player 可以具有比 actor.

更多的属性

有没有办法不仅在 new 方法中做到这一点,而且在其他方​​法中,如 player:move(x, y) 将调用 actor:move(x, y)self:move(x, y) 但使用附加代码?

我使用这种模式在模块中制作 classes:

local actor = {}

function actor:new(x, y, s)

    self.__index = self

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

        sprite = s
    }, self)
end

-- methods

return actor

执行此操作的一个好方法是使用一个单独的函数来初始化您的实例。然后你可以简单地在继承的 class.

中调用基础 classes 初始化

就像这个例子: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