Nested tables and references
Tables can hold other tables, and copying one needs explicit work.
In this page:
Nested tables and references
A table can contain tables to build grids, records and trees. Assignment only copies the reference, so two variables can point to the same table. A shallow copy duplicates only the top level, while nested tables remain shared, so a deep copy needs recursion.
Note:
Two tables are equal with == only if they are the very same object.
Example: Nested tables and references
local grid = {{1, 2}, {3, 4}}
print(grid[2][1], #grid)
local a = {1, 2}
local b = a
b[1] = 99
print(a[1], a == b, {} == {})
local function shallow(t)
local c = {}
for k, v in pairs(t) do c[k] = v end
return c
end
local copy = shallow(grid)
copy[1][1] = "shared"
print(grid[1][1])
-- Output:
-- 3 2
-- 99 true false
-- shared
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Believing local b = a makes a separate copy
- Comparing two tables with == to test their contents
- Making a shallow copy and modifying a nested table
Chapter Summary
- Tables can nest
- Assignment shares a reference
- A shallow copy shares nested tables
- == compares identity for tables
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: