So I was just running into an issue that was driving me crazy until I finally figured it out. I’m not sure if this is intended behavior or has just always been a thing since the Lua base language was created. But using table.clone() on nested tables doesn’t work super intuitively.
Let’s say I have:
local table1 = {
A = {1},
B = {2},
C = {3},
}
if I call table.clone() on table1. I would expect a new copy to be made not only of table1, but of all it’s sub-entries as well. Such that editing the new table wouldn’t affect the original one.
local table2 = table.clone(table1)
for i,v in pairs(table2) do
table2[i][1] = table2[i][1] + 1
end
for i,v in pairs(table1) do
print(i,v[1])
end
for i,v in pairs(table2) do
print(i,v[1])
end
In the output I would hope to see:
A,1
B,2
C,3
A,2
B,3
C,4
however instead I see:
A,2
B,3
C,4
A,2
B,3
C,4
because all the sub-entries of table2 are just a reference to the same entires in table1, despite table.clone() being called.
Just a question; do you know of any way to deep-copy a nested table without using a custom-made function? It’d be lovely to have a way to do this quickly and easily
Currently you must write a util function for this. There’s several table themed util libraries you can use that others have written if you prefer not to do that.
Shallow copy is the expected behavior of copy functions that don’t otherwise specify that they do a deep copy.
Also noticed you can use SharedTables’s SharedTable.clone(table, deepCopyBoolean) which deep copies another SharedTable, but probably not worth the setup if you’re not actually using the shared part of it.