Skip to content

Instantly share code, notes, and snippets.

@Zbizu
Last active January 19, 2022 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Zbizu/ed0b7386a632ac4e953fb8232e475595 to your computer and use it in GitHub Desktop.
Save Zbizu/ed0b7386a632ac4e953fb8232e475595 to your computer and use it in GitHub Desktop.
[Lua] Clone a table without references
-- 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