【问题标题】:Lua inheritance and methodsLua继承和方法
【发布时间】:2021-08-22 01:49:45
【问题描述】:

如何从类actor 继承一个新类player 并使用相同的参数在方法player:new(x, y, s) 中调用方法actor:new(x, y, s)。我需要使player: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

【问题讨论】:

    标签: oop inheritance lua love2d


    【解决方案1】:

    这样做的一个好方法是使用一个单独的函数来初始化您的实例。然后您可以简单地在继承的类中调用基类初始化。

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

    【讨论】:

    • 感谢您的宝贵时间和答案!
    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 2012-04-25
    • 2014-06-10
    • 2014-10-04
    • 2019-06-21
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多