cocos2dx-lua里面class的实现的一些问题记录和思考

首先要理解lua的class,要先理解metatable的作用和__index以及lua调用table里面的函数的时候搜索函数的逻辑:

1、直接当前表里面搜索函数 如果存在,直接调用,不存在继续

2、如果表里面不存在调用的函数,会查找表的metatable的__index

       a、如果__index是一个表,则在该表里面查找,回到第一步

       b、如果__index是一个函数,则传递要查找的表、和函数名字给__index这个函数,如果函数返回一个函数则执行该函数,或者直接提示找不到函数,或者返回另外一个表,则又回到第一步在这个表里面查找


下面来看看cocos的lua的class的实现方式

class的声明


function class(classname, ...)

    local cls = {__cname = classname}   设置类的名字


    local supers = {...}

    for _, super in ipairs(supers) do  遍历第二个参数

        local superType = type(super)

        assert(superType == "nil" or superType == "table" or superType == "function",

            string.format("class() - create class \"%s\" with invalid super class type \"%s\"",

                classname, superType))


        if superType == "function” then   如果参数是一个函数  则将这个函数设置为类的__create函数

            assert(cls.__create == nil,

                string.format("class() - create class \"%s\" with more than one creating function",

                    classname));

            -- if super is function, set it to __create

            cls.__create = super

        elseif superType == "table” then  如果是一个表

            if super[".isclass"] then  如果是一个c++的对象

                -- super is native class

                assert(cls.__create == nil,

                    string.format("class() - create class \"%s\" with more than one creating function or native class",

                        classname));

                cls.__create = function() return super:create() end  __create函数就等于调用c++类的create函数

            else

                -- super is pure lua class

                cls.__supers = cls.__supers or {}   设置

                cls.__supers[#cls.__supers + 1] = super

                if not cls.super then

                    -- set first super pure lua class as class.super

                    cls.super = super

                end

            end

        else

            error(string.format("class() - create class \"%s\" with invalid super type",

                        classname), 0)

        end

    end


    cls.__index = cls

    if not cls.__supers or #cls.__supers == 1 then  如果只有一个父类  则设置metatable为一个表

        setmetatable(cls, {__index = cls.super})

    else

        setmetatable(cls, {__index = function(_, key)  如果有多个父类,则设置metatable为一个函数,通过函数查找对应的函数

            local supers = cls.__supers 

            for i = 1, #supers do

                local super = supers[i]

                if super[key] then return super[key] end

            end

        end})

    end


    if not cls.ctor then

        -- add default constructor

        cls.ctor = function() end

    end

    cls.new = function(...)

        local instance

        if cls.__create then

            instance = cls.__create(...)

        else

            instance = {}

        end

        setmetatableindex(instance, cls)

        instance.class = cls

        instance:ctor(...)

        return instance

    end

    cls.create = function(_, ...)

        return cls.new(...)

    end


    return cls

end


函数里面用到的setmetatableindex的实现

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)   另外总觉得这一句有问题,不是应该是setmetatableindex(mt.__index, index)吗,如果__index是函数,也应该扩展让其会搜索其metatable或者自身之后,再使用setmetatableindex(mt, index),才会生效,请大神指点迷津

        end

    end

end

setmetatableindex = setmetatableindex_






这里有两种情况:


对于从C++对象派生的情况,new出来的实际上并不是一个table而是一个userdata


这个时候其函数从两个地方来:

a、getmetatable(instance)[funcname]——————>来自于C++类和C++类的父类

这里有一个不解的地方是这个所有的函数都位于metatable中而不是metatable的__index域中,是怎么做到从metatable中查找域而不是metatable的__index域呢。通过输出可以看到每一个metatable中其实是有__index域的,并且是一个函数,不过没有找到实现


b、tolua.getpeer(instance)[funcname]——————>来自于getpeer返回的table以及其metatable的__index域(递归)

而对于从纯lua对象派生的类,new出来的实例也是一个table


对于a的问题,目前猜测是这样,因为metatable的__index是一个函数,所以我猜测是这个函数做了一些特殊操作,因此进行了如下实验:

因为我们知道当在一个表或者userdata中找不到某个域的时候,回去__index中查找,如果还是__index是一个函数,则传入__index的参数是这个userdata或者表本身和要查找的域的名字,所以我们考虑设置__index函数为如下的函数:

function myindex(t, key)

return getmetatable(t)[key]

end

这样就告诉表或者userdata,如果找不到某个函数,就将自己和key传递个__index然后从自己的metatable中查找。实验如下:

local Class1 = {}


function Class1:test()

    print('test')

end


local Class2 = {}


local myIndex = function(t, key)

    return getmetatable(t)[key]

end


Class1.__index = myIndex

function Class2:new()

    local o = {}

    local t  = {__index = myIndex}

    setmetatable(o, t)

    local t1  = {__index = myIndex}

    setmetatable(t, t1)

    setmetatable(t1, Class1)

    return o

end

local ta = Class2.new()

ta:test()

这段代码输出为test,也就是说可以调用到Class1的test函数

上面的代码Class1就只是o的metatable的metatable的metatable,和我们cocos2dx返回的userdata的结构类似了

我们来看看这段代码是如何做到的:

首先Class1有一个test函数

然后Class2只是为了给new一个作用域,主要看new的代码

新建一个表o

设置o的metatable为t,t的__index为上面说到的函数

然后设置t的为metable为t1,t1的__index也为上面的函数

最后设置t1的metatable为Class1,Class1的__index也是myIndex

来看调用关系

1、在ta中查找,找不到,继续

2、ta中没有通过ta的metatable(t)的__index查找,__index为函数,则将ta和’test'作为参数传递给该函数,该函数通过getmetatable(ta)即(t)查找,t中也没有,继续

3、t中没有,通过t的metatable(t1)的__index查找,也为函数,将t和’test'作为参数传递给函数,通过getmetatable(t)即(t1)中查找,t1中也没有,继续

4、t1中没有,通过t1的metatable(Class1)的__index查找,为函数,将t1和’test'作为参数传递给函数,通过getmetatable(t1)即(Class1)查找,找到,所以返回Class1的test函数


说明这种实现方式是可行的,那么再来看看cocos2dx是否是这样实现的。

通过创建一个派生自cocos2dx的一个userdata test,然后尝试输出下面的函数

print(getmetatable(test).__index(test, "visit”))

输出为函数,说明找到了函数,然后我们尝试重载一个函数来看看。



local tmpmetatablefunc = getmetatable

getmetatable = function(ta)

    print(ta)

    return tmpmetatablefunc(ta)

end


function ViewBase:setPosition(x, y)

    print("--------")

    local tmpindex = getmetatable(self).__index

    getmetatable(self).__index = function(t1, key) print(t1, key) return tmpindex(t1, key) end

    local a = getmetatable(self).__index(self, 'setPosition')

    print(a)

    local b = getmetatable(self)['setPosition']

    print("ttttttttttt")

    print(a == b)

    print("callfunction")

    a(self, x, y)

    --getmetatable(self)['setPosition'](self, x, y)

    print("viewbase.setPosition")

end


有一些为测试代码,不管他,重点是标红的代码。通过__index来获取setPosition函数

当ViewBase重新定一个setPosition函数的时候,如果用这种方式来重载的时候,我发现出现了递归调用,通过上面的测试代码发现是因为通过__index查找到的函数就是我们在这里定义的ViewBase:setPosition本身,而不是我们想调用的其基类的setPosition。由此还可以推断出另外一个事实,那就是tolua++中__index并不是仅仅搜索metatable,还是对tolua.getpeer进行搜索,因为通过上面的Class的定义我们知道ViewBase是放在tolua.getpeer的表的metatale的__index中的。但是这里还没有证明__index会搜索getmetatable的key。


这里我们修改一下函数的名字

local tmpmetatablefunc = getmetatable

getmetatable = function(ta)

    print(ta)

    return tmpmetatablefunc(ta)

end


function ViewBase:setPosition1(x, y)

    print("--------")

    local tmpindex = getmetatable(self).__index

    getmetatable(self).__index = function(t1, key) print(t1, key) return tmpindex(t1, key) end

    local a = getmetatable(self).__index(self, 'setPosition')

    print(a)

    local b = getmetatable(self)['setPosition']

    print("ttttttttttt")

    print(a == b)

    print("callfunction")

    a(self, x, y)

    --getmetatable(self)['setPosition'](self, x, y)

    print("viewbase.setPosition")

end

我们重新定义的函数叫setPosition1,这样搜索的时候就不会在tolua.getpeer中找到setPosition了。然后调用setPosition1来设置位置,发现成功了,那就证明

__index函数搜索会搜索metatable的域了。

并且综合上面的分析,还可以知道其搜索顺序是先搜索tolua.getpeer中的函数,再搜索metatable,这样就可以做到优先使用我们重新定义的函数而不是积累的函数,做到重定义父类函数的功能。

这里分析了这么多,其实还不如直接去看tolua++的源代码,不过因为时间有限,对lua的c接口还不熟悉,所以仅先通过在lua这边看到的现象进行一些分析知其然,以后再仇视时间区看看tolua++代码和lua代码,之其所以然吧。


对于C++类的派生,创建的时候其实是先从C++创建一个原始的userdata,然后通过设置其getpeer的metatable来扩展其成员函数

其搜索顺序应该是先b后a

如果访问的是C++的原生函数,则是从getmetatable获取到,如果是派生出来的函数,则通过tolua.getpeer的表来得到其类或者父类的域


这个时候其函数和成员变量都来自于

instance[funcname]  ——————>instance自身以及其metatable的__index域(递归)


这里是直接创建一个表,然后将其metatable指向其类,然后在访问instance的域的时候就会找到其类或者父类的域了


而如果要调用父类的函数而不是调用自己重载的函数,可以使用如下函数:

function getBaseFunc(data, name)

local a

if data.super ~= nil then

a = data.super[a]

end

if a == nil then

a = getmetatable(data)[a]

end

return a

end


如果调用指定级数的函数


可以直接使用ClassName.func(self, param)


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值