lua oop如何调用超类构造函数

时间:2014-06-04 10:04:11

标签: oop lua

我需要帮助在LUA上编写OOP。我关注this tutorial。但是,我不知道如何调用超类构造函数。

-- Base class
setmetatable(BaseClass, {
  __call = function (cls, ...)
    local self = setmetatable({}, cls)
    self._value = '12345'
    return self
  end,
})

-- Derived Class
setmetatable(DerivedClass, {
  __index = BaseClass, -- this is what makes the inheritance work
  __call = function (cls, ...)
    local self = ???
    -- How to call superclass constructor here?
    return self
  end,
})
function DerivedClass:haha()
  print(self._value)
  self._value = 0 -- Works on _value for example
  print(self._value)
end

-- Create instance
instance = DerivedClass()
assert_not_nil(instance._value) -- instance._value always nil here...
instance:haha() -- print 12345 and print 0

我试过以下 local self = setmetatable({}, BaseClass)local self = setmetatable({}, BaseClass())

它们都不起作用。

此外,如果我执行代码cls,{_ 1}}引用的参数是什么?

由于

0 个答案:

没有答案