Quick class的继承问题

最近发现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

哪来的create方法 代码不全怎么看

你这个是什么版本的 , setmetatableindex_ 这个我也没有

另外你这么写也不是继承啊 class 第2个参数是luatable才是继承

local childClz = class(“child”, function ()
return base.new()
end)
应该写成这样的

setmetatableindex_ 是lua table自带的

— Begin quote from ____

引用第1楼ColaZhang于2015-05-12 19:08发表的 :
哪来的create方法 代码不全怎么看 http://www.cocoachina.com/bbs/job.php?action=topost&tid=300332&pid=1305731

— End quote

引擎版本3.4

这个代码是 function.lua 里面的关于class的封装部分的

— Begin quote from ____

引用第3楼ColaZhang于2015-05-12 19:15发表的 :
另外你这么写也不是继承啊 class 第2个参数是luatable才是继承 http://www.cocoachina.com/bbs/job.php?action=topost&tid=300332&pid=1305739

— End quote

return出来的也是lua table

— Begin quote from ____

引用第4楼lstarboy于2015-05-12 19:39发表的 :

local childClz = class(“child”, function ()
return base.new()
end)
应该写成这样的 http://www.cocoachina.com/bbs/job.php?action=topost&tid=300332&pid=1305754

— End quote

new 和 create是一样的, 在最后把new 赋值给了 create

这个代码是出自function.lua , 引擎版本3.4

— Begin quote from ____

引用第5楼adodo08于2015-05-12 21:52发表的 :
setmetatableindex_ 是lua table自带的 http://www.cocoachina.com/bbs/job.php?action=topost&tid=300332&pid=1305806

— End quote

不是,这个函数是在 cocos.cocos2d.function.lua 里面自定义的

引擎版本3.4

第二段代码来自 cocos.cocos2d.function.lua

在 quick 3.3 里面是这样用的:


local base = class("base")
function base:ctor()
    print(" base ctor ")
end

local childClz = class("child", function()
    return base.new()
end)

function childClz:ctor()
    print(" child ctor ")
end

local c = childClz.new()

output:


cocos2d:  base ctor
cocos2d:  child ctor