# [LUA]Deep Copy of any Table

Page 1 of 1

## 0 Replies - 1452 Views - Last Post: 23 May 2010 - 06:51 PM

### #1 athlon32

• D.I.C Regular

Reputation: 117
• Posts: 363
• Joined: 20-August 08

# [LUA]Deep Copy of any Table

Posted 23 May 2010 - 06:51 PM

Description: Should work perfectly in Lua 5.1By defualt Lua makes shallow copies when one variable is assigned to another. That is, its variables act like pointers, and changes to one are reflected in all others pointing to the same thing. This function makes a deep copy (it actually assigns the values of one table to another). It is recursive too, so even tables containing tables will be handled properly.
-- By defualt Lua makes shallow copies when one variable is assigned to another.
-- That is, its variables act like pointers, and changes to one are reflected
-- in all others pointing to the same thing. This function makes a deep copy (it
-- actually assigns the values of one table to another). It is recursive too, so
-- even tables containing tables will be handled properly.

function deepcopy(a, b)
if type(a) ~= "table" or type(b) ~= "table" then
error("both parameters must be of type table but recieved " ..type(a)..
" and " .. type(b));
else
for k,v in pairs(a) do
-- if the type is a table, we'll need to recurse.
if type(v) ~= "table" then
b[k] = v;
else
local x = {}
deepcopy(v, x);
b[k] = x;
end
end
end
return b;
end

-- An example demonstration
t = { z = {l = 5}} -- any ol' table
shallow = t; -- will change as 't' does
deep = deepcopy(t, {}); -- not dependant on 't'

-- modify t and see subsequent changes
t.z.l = 34;
print(shallow.z.l) -- new 34
print(deep.z.l) -- original 5

Is This A Good Question/Topic? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }