Last active
January 19, 2022 19:01
-
-
Save Zbizu/ed0b7386a632ac4e953fb8232e475595 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