Menu
CoddyTech

Clone and Shared References

Lesson 13 of 29 in Coddy's Lua for Luau Developers course.

Luau table.clone makes a shallow copy; Lua 5.1 has no equivalent standard helper. For a plain record, copy its present key-value pairs into a new table. Nested table values still refer to the original objects unless you deliberately copy them too. This behavior is already familiar from Luau, but the missing helper can tempt a misleading shortcut: assignment only creates another reference to the same outer table. Metatable-bearing objects need a separate copy policy; the plain-record loop shown here does not promise to preserve every detail of table.clone. Decide which levels should be independent before implementing a port.

Luau

local a = {label="old", child={n=1}}
local b = table.clone(a)
b.label = "new"
b.child.n += 1
print(`{a.label}:{a.child.n}`)

Lua 5.1

local a = {label="old", child={n=1}}
local b = {}
for k,v in pairs(a) do b[k]=v end
b.label = "new"
b.child.n = b.child.n + 1
print(a.label .. ":" .. a.child.n)

Porting trap

A shallow copy protects outer fields only. Mutating a nested table can still change what the original record observes.

challenge icon

Challenge

Easy

Input is an integer original value and integer replacement. Create a record, shallow-copy it, replace the copy value, and return original:copy.

Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Try it yourself

local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for Luau Developers

Practice on your own: Online Lua compiler