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
endAll lessons in this course
- table.sort with Comparators
- table.concat and table.move
- Deep Copy and Shallow Copy
- Transforming Tables: map, filter, reduce