0Pricing
Lua Academy · Lesson

Deep Copy and Shallow Copy

Implement recursive deep copy and understand reference semantics.

Reference Semantics in Lua

In Lua, assigning a table to another variable copies the reference, not the data. Both variables point to the same table.

local a = {1, 2, 3}
local b = a
b[1] = 99
print(a[1])  -- 99, a is affected!

Shallow Copy

A shallow copy creates a new table with the same top-level keys and values. Nested tables are still shared.

local function shallowCopy(t)
  local copy = {}
  for k, v in pairs(t) do copy[k] = v end
  return copy
end

All lessons in this course

  1. table.sort with Comparators
  2. table.concat and table.move
  3. Deep Copy and Shallow Copy
  4. Transforming Tables: map, filter, reduce
← Back to Lua Academy