🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Copying Tables

Copying a table means making a second table with the same values. A shallow copy shares nested tables, while a deep copy rebuilds them too.

A shallow copy shares nested tables

Copying each top level entry gives a new outer table. The nested table inside is still the same table, so a change through the copy shows in the original.

local original = {name = "box", inner = {count = 5}}
local copy = {}
for key, value in pairs(original) do
  copy[key] = value
end
copy.inner.count = 9
print(original.inner.count, copy.inner.count)

Top level changes stay separate

Changing a top level field touches only one table. The other table keeps its own value for that field.

local original = {name = "box", inner = {count = 5}}
local copy = {}
for key, value in pairs(original) do
  copy[key] = value
end
copy.name = "bag"
print(original.name, copy.name)
print(original.inner.count, copy.inner.count)

A deep copy rebuilds nested tables

The copy function calls itself for any table value. Changing the copy nested table then leaves the original alone.

local function deepCopy(value)
  if type(value) ~= "table" then
    return value
  end
  local copy = {}
  for key, item in pairs(value) do
    copy[key] = deepCopy(item)
  end
  return copy
end
local original = {name = "box", inner = {count = 5}}
local copy = deepCopy(original)
copy.inner.count = 9
print(original.inner.count, copy.inner.count)

Example

local function deepCopy(value)
  if type(value) ~= "table" then
    return value
  end
  local copy = {}
  for key, item in pairs(value) do
    copy[key] = deepCopy(item)
  end
  return copy
end
local original = {name = "box", inner = {count = 1}}
local shallow = {}
for key, value in pairs(original) do
  shallow[key] = value
end
local deep = deepCopy(original)
shallow.inner.count = 2
deep.inner.count = 3
print(original.inner.count, shallow.inner.count, deep.inner.count)

Key points

  • Shallow copy: a shallow copy copies only the top level keys and values.
  • Shared nested table: a shared nested table is one table reached from both the original and the copy.
  • Top level: top level values such as numbers and strings are copied by value, so changing one copy leaves the other alone.
  • Deep copy: a deep copy rebuilds every nested table, so no nested table is shared.
  • Recursion: recursion means a function calls itself on each nested table to rebuild it.

In this example, the original gains both a shallow copy and a deep copy. Changing the shallow copy nested count also changes the original, because they share that nested table. Changing the deep copy nested count leaves the other two alone, because the deep copy rebuilt it.

Note

a deep copy of a table that contains itself would loop forever, so this lesson copies tables without cycles.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

After a shallow copy, what happens when you change a nested table through the copy?