Sometimes it’s useful to be able to copy or “clone” a table. Lua provides no built-in function to copy tables, but the following methods can help.
A “shallow copy” is useful for copying a table that’s one level deep — meaning, a basic array or dictionary table without any nested tables inside it.
A dictionary table can be shallow copied by looping over the original table’s keys using
pairs and assigning them to another table:
In practice, the copy can be made as follows:
For arrays, the Lua
unpack() function can do most of the work:
Sometimes a shallow copy isn’t enough. Tables with nested tables inside it must be copied with a recursive function:
With the function in place, a deep copy can be made as follows: