← Back to Lua Course | Chapter 4: Tables | Lesson 6 of 7

Nested tables and references

Tables can hold other tables, and copying one needs explicit work.

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

lua
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
Common Mistakes
  1. Believing local b = a makes a separate copy
  2. Comparing two tables with == to test their contents
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.