Source code explanation of the clone function in cocos2dx lua
The clone function of cocos2dx is a deep copy and a full copy. This Code does not have much content, but it is a bit dizzy for the first time. I will write down the explanation and share it with you. The source code is interpreted as follows:
Function clone (object) -- clone function local lookup_table ={} -- create a table to record the local function _ copy (object) -- _ copy (object) function for copying if type (object) ~ = "Table" then return object --- directly return the object if the content is not table (for example, directly return the number \ This string if it is a number \ string) elseif lookup_table [object] then return lookup_table [object] -- This is used for Recursive dropping. If this table has been copied, return the end local new_table ={} lookup_table [object] = new_table -- create a level-2 sub-table for copying the new_table record and put it in lookup_table [object. for key, value in pairs (object) do new_table [_ copy (key)] = _ copy (value) -- traverse object and Recursion _ copy (value) copy the data in each table. end return setretriable (new_table, getretriable (object) -- after each traversal, set the resumable key value end return _ copy (object) for the specified table -- return the cloned object table pointer/address end
Example:
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) -- add the print function to demonstrate the process of output replication. end return setretriable (new_table, getretriable (object) end return _ copy (object) -- returns the cloned object table pointer/address 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 () local newtable2 = clone (myPolygon)
----------- 1200 output content
1 300
2 500
2 table: 0x7ffa43d06930
1 100
2 200
1 300
2 400
Table: 0x7ffa43d06610 table: 0x7ffa43d068f0
Abc --- the output content when copying Table a is followed by the output content of table 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