Back to Blog

Learn Lua in Neovim: Table References vs Copies — The Copy Trap, Shallow & Deep Copy | Episode 22

Sandy LaneSandy Lane

Video: Learn Lua in Neovim: Table References vs Copies — The Copy Trap, Shallow & Deep Copy | Episode 22 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Lua in Neovim: Table References vs Copies — The Copy Trap, Shallow & Deep Copy

In Lua, assigning a table to a new variable does not create a copy but rather a reference to the same table, which can lead to unintended side effects when modifying data. This guide explains the difference between references and copies, demonstrates how to create a shallow copy that duplicates only the top-level keys, and builds a recursive deep copy function to fully clone nested tables.

Code

-- Original table
local a = { score = 99 }

-- Reference assignment: b points to the same table as a
local b = a
b.score = 100
print(a.score)  -- Output: 100 (both a and b share the same table)

-- Shallow copy: copies only top-level keys
local function shallow_copy(t)
  local copy = {}
  for k, v in pairs(t) do
    copy[k] = v
  end
  return copy
end

local c = { name = "Alice", scores = { math = 90, science = 95 } }
local d = shallow_copy(c)
d.name = "Bob"
d.scores.math = 80
print(c.name)          -- Output: Alice (independent)
print(c.scores.math)   -- Output: 80 (nested table still shared!)

-- Deep copy: recursively copies all nested tables
local function deep_copy(t)
  if type(t) ~= "table" then return t end
  local copy = {}
  for k, v in pairs(t) do
    copy[k] = deep_copy(v)
  end
  return copy
end

local e = deep_copy(c)
e.scores.science = 70
print(c.scores.science)  -- Output: 95 (fully independent copy)

Key Points

  • Assigning one table to another variable copies the reference, not the table itself.
  • Modifying a table through any reference affects all variables pointing to it.
  • A shallow copy duplicates only the top-level keys, leaving nested tables shared.
  • A deep copy recursively clones all nested tables, creating a fully independent copy.
  • Use shallow copy for simple, flat tables and deep copy when nested structures must be isolated.