PcoWSkbVqDnWTu_dm2ix

5 min

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.

Shallow Copies

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.

Dictionaries

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:

Arrays

For arrays, the Lua unpack() function can do most of the work:

Deep Copies

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:

Tags:
  • cloning
  • tables