展会信息港展会大全

关于cocos2dx lua中的clone函数的源码解读
来源:互联网   发布日期:2015-09-27 15:06:11   浏览:2228次  

导读: cocos2dx的clone函数,是深拷贝,完全的拷贝,这段代码内容不多,不过第一次看还是有点晕,我把解读记下来分享一下. 源码解读: function clone(object)--clon...

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, y=0},

{x=-5, y=4},

{x=0, 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

赞助本站

人工智能实验室
AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港