Table.clone() Doesn't Work Intuitively With Nested Tables

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.

1 Like

table.clone only performs a shallow (top level) copy of the table data: table | Documentation - Roblox Creator Hub

Original design description here rfcs/docs/function-table-clone.md at b14fb7798f9024e0e06b961bccc2b421a746de2f · luau-lang/rfcs · GitHub

1 Like

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

2 Likes

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.

2 Likes

Right; thanks for this.

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.

1 Like

Here’s the Nevermore utility library which will do what you want!

1 Like