最近发现class的继承好像有点问题,例如如下代码:
local base = class("base")
function base:ctor()
print(" --- base ctor called --- ")
end
local childClz = class("child", function ()
return base:create()
end)
function childClz:ctor( )
print(" --- child ctor called --- ")
end
local c = childClz:create()
```
输出的结果是调用父类构造函数2次,不调用子类构造函数。追踪class的实现,发现是在这个函数里面:
local setmetatableindex_
setmetatableindex_ = function(t, index)
if type(t) == "userdata" then
local peer = tolua.getpeer(t)
if not peer then
peer = {}
tolua.setpeer(t, peer)
end
setmetatableindex_(peer, index)
else
local mt = getmetatable(t)
if not mt then mt = {} end
if not mt.__index then
mt.__index = index
setmetatable(t, mt)
elseif mt.__index ~= index then
setmetatableindex_(mt, index)
end
end
end
setmetatableindex = setmetatableindex_
```
当按第一段代码调用子类的create的时候,会先创建父类对象,然后设置metatable和__index,然后创建子类,这个时候,__index已经被设置,就走了最后一个elseif。
访问ctor的时候,会直接访问到父类的 ctor去。
现在的问题如下:
1、最后一个elseif的代码到底什么意思?
给元表设置 __index ,怎么看都不懂。。。。
2、这个继承失败,是因为我使用的方式不对,还是代码bug