微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Lua 继承和方法

如何解决Lua 继承和方法

如何从类 player 继承新类 actor 并使方法 actor:new(x,y,s)调用方法 player:new(x,s) 具有相同的参数。我需要使 player:new 相同但具有附加参数,以便 player 可以拥有比 actor 更多的属性

有没有办法不仅在 new 方法中执行此操作,而且在其他方​​法中执行此操作,例如 player:move(x,y)调用 actor:move(x,y)self:move(x,y),但需要附加代码

我使用这种模式在模块中创建类:

local actor = {}

function actor:new(x,s)

    self.__index = self

    return setMetatable({
        posx = x,posy = y,sprite = s
    },self)
end

-- methods

return actor

解决方法

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

就像这个例子: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,s,name)
  actor.init(self,x,s)
  self.name = name or "John Doe"
end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。