cocos2dx lua clone实现解析

来源:互联网 发布:python 没有cv2.cv 编辑:程序博客网 时间:2024/06/06 02:42

cocos2dx lua clone使用是

local a = clone(b)
clone的源代码

function clone(object)    local lookup_table = {}                                    local function _copy(object)        if type(object) ~= "table" then
            return object        elseif lookup_table[object] then   --当一个table有两个相同的table就会用到它            return lookup_table[object]        end        local new_table = {}        lookup_table[object] = new_table        for key, value in pairs(object) do            new_table[_copy(key)] = _copy(value)        end        return setmetatable(new_table, getmetatable(object))    end    return _copy(object)end
clone的思想总结就是1,遍历 2 ,递归。

通过遍历key ,找到value,递归_copy(value).

如果value类型不是table,则返回object给 new_table[_copy(value)]赋值;

如果类型是table的话,就相当于执行_copy(value),将value看成是一个table,

然后执行

      for key, value in pairs(object) do            new_table[_copy(key)] = _copy(value)        end

...

直到value不是table为止。返回一个new_table数组引用。

0 0