Menu
CoddyTech

Aliasing and Shallow Copies

Lesson 25 of 48 in Coddy's Lua for Go Developers course.

Go slice assignment shares a backing array; an explicit copy into new storage isolates outer elements. Pointer or slice elements can still refer to shared nested state. Lua table assignment similarly shares a table, while copying entries into a new table is shallow. Define which nested mutable values must be copied separately to satisfy ownership requirements.

Go

package main
import ("fmt")

func main(){
a:=[]int{1}; b:=make([]int,len(a)); copy(b,a); b[0]=9; fmt.Println(a[0])
}

Lua

local original = {n = 1, nested = {value = 2}}
local copy = {}
for key, value in pairs(original) do
  copy[key] = value
end
copy.n = 9
copy.nested.value = 7
print(original.n .. ":" .. original.nested.value)

Porting trap

A copied outer collection can still retain shared nested objects.

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 Go Developers

Practice on your own: Online Lua compiler