Aliasing and Shallow Copies
Lesson 25 of 48 in Coddy's Lua for GDScript Developers course.
Assigning a GDScript dictionary to another variable shares the same container. Calling duplicate() creates a new outer dictionary, while nested arrays and dictionaries remain shared unless a deeper copy is requested. Lua table assignment likewise shares a table, but Lua 5.1 provides no built-in duplicate method. A loop through pairs can copy the outer entries. Updating a scalar field in that copy leaves the original field unchanged. Updating a nested table still affects both outer tables because each stores the same nested reference. Decide which nested state must be independently owned before translating a resource or inventory copy.
GDScript 4
extends SceneTree
func _init():
var original = {"count": 2, "items": ["key"]}
var copied = original.duplicate()
copied["count"] = 9
copied["items"].append("map")
print(str(original["count"]) + ":" + str(copied["count"]) + ":" + str(original["items"].size()))
quit()Lua 5.1
local original = {count = 2, items = {"key"}}
local copied = {}
for key, value in pairs(original) do copied[key] = value end
copied.count = 9
table.insert(copied.items, "map")
print(original.count .. ":" .. copied.count .. ":" .. #original.items)Porting trap
A Lua copying loop is shallow, like GDScript duplicate() with its default argument. It is not a replacement for every use of duplicate(true).
Challenge
EasyInput 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules5Tables as Collections
Arrays as Dense TablesDictionaries and pairsSets and MembershipAliasing and Shallow CopiesRecap: Count InventoryPractice on your own: Online Lua compiler