-
-
Save Codinablack/56fe25df61a58914ad46f20c3a822e38 to your computer and use it in GitHub Desktop.
[Lua] Clone a table without references
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- creates a full copy of a table | |
-- changing the value of copied table doesn't touch the original anymore | |
-- warning: using methods on "copied" userdata will still affect original object | |
local a = { | |
["abc"] = {1, 2}, | |
[1] = {4, {2}} | |
} | |
function cloneTable(t) | |
local o = {} | |
for k, v in pairs(t) do | |
if type(v) == "table" then | |
o[k] = cloneTable(v) | |
else | |
o[k] = v | |
end | |
end | |
return o | |
end | |
-- create a copy of table a without references to it | |
local b = cloneTable(a) | |
-- test if it works | |
b[1][2][1] = 3 | |
print(a[1][2][1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment