关于cocos2dx lua中的clone函数的源码解读

关于cocos2dx lua中的clone函数的源码解读,第1张

概述cocos2dx的clone函数,是深拷贝,完全的拷贝,这段代码内容不多,不过第一次看还是有点晕,我把解读记下来分享一下. 源码解读: function clone(object)--clone函数 local lookup_table = {}--新建table用于记录 local function _copy(object)--_copy(object)函数用于实现复制 cocos2dx的clone函数,是深拷贝,完全的拷贝,这段代码内容不多,不过第一次看还是有点晕,我把解读记下来分享一下. 源码解读:
function clone(object)--clone函数    local lookup_table = {}--新建table用于记录    local function _copy(object)--_copy(object)函数用于实现复制        if type(object) ~= "table" then             return object   ---如果内容不是table 直接返回object(例如如果是数字\字符串直接返回该数字\该字符串)        elseif lookup_table[object] then            return lookup_table[object]--这里是用于递归滴时候的,如果这个table已经复制过了,就直接返回        end        local new_table = {}        lookup_table[object] = new_table--新建new_table记录需要复制的二级子表,并放到lookup_table[object]中.        for key,value in pairs(object) do            new_table[_copy(key)] = _copy(value)--遍历object和递归_copy(value)把每一个表中的数据都复制出来        end        return setMetatable(new_table,getMetatable(object))--每一次完成遍历后,就对指定table设置Metatable键值    end    return _copy(object)--返回clone出来的object表指针/地址end 


实例示范:
function clone(object)    local lookup_table = {}    local function _copy(object)        if type(object) ~= "table" then             return object         elseif lookup_table[object] then            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)            print(key,value)--这句添加print函数 演示输出复制的过程        end        return setMetatable(new_table,getMetatable(object))    end    return _copy(object)--返回clone出来的object表指针/地址end local a = {[{100,200}] = { 300,400},200,{ 300,500},abc = "abc"}local mypolygon = { color="blue",thickness=2,npoints=4,{x=0,y=0},{x=-10,{x=-5,y=4},y=4} }local newtable = clone(a)local newtable2 = clone(mypolygon)

-----------输出内容 1 200 1 300 2 500 2 table: 0x7ffa43d06930 1 100 2 200 1 300 2 400 table: 0x7ffa43d06610 table: 0x7ffa43d068f0 abc abc ---以上是复制表a时的输出内容 后面以下是表mypolygon的输出内容 x 0 y 0 1 table: 0x7ffa43d064f0 x -10 y 0 2 table: 0x7ffa43d06a60 x -5 y 4 3 table: 0x7ffa43d06af0 x 0 y 4 4 table: 0x7ffa43d06b80 npoints 4 thickness 2 color blue 总结

以上是内存溢出为你收集整理的关于cocos2dx lua中的clone函数的源码解读全部内容,希望文章能够帮你解决关于cocos2dx lua中的clone函数的源码解读所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1022451.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存