Cloning Tables

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:


1local function shallowCopy(original)
2 local copy = {}
3 for key, value in pairs(original) do
4 copy[key] = value
5 end
6 return copy
7end
8

In practice, the copy can be made as follows:


1local original = {
2 key = "value",
3 engine = "Roblox",
4 playerID = 505306092
5}
6local clone = shallowCopy(original)
7
8for key, value in pairs(clone) do
9 print(key, value)
10end
11

The previous code has the following expected output:


1playerID 505306092
2key value
3engine Roblox
4

Arrays

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


1local original = {1, 3, 5, 7, 9}
2local clone = {unpack(original)}
3
4for i = 1, #clone do
5 print(clone[i])
6end
7

The previous code has the following expected output:


11
23
35
47
59
6

Deep Copies

Sometimes a shallow copy isn't enough. Tables with nested tables inside it must be copied with a recursive function:


1local function deepCopy(original)
2 local copy = {}
3 for k, v in pairs(original) do
4 if type(v) == "table" then
5 v = deepCopy(v)
6 end
7 copy[k] = v
8 end
9 return copy
10end
11

With the function in place, a deep copy can be made as follows:


1local original = {
2 key = "value",
3 playerInfo = {
4 playerID = 505306092,
5 playerName = "PlayerName"
6 },
7 otherInfo = {
8 {
9 {1, 3, 5, 7, 9}
10 }
11 }
12}
13local clone = deepCopy(original)
14
15print(clone["playerInfo"]["playerID"])
16print(clone["otherInfo"][1][1][4])
17

The previous code has the following expected output:


1505306092
27
3