Menu
CoddyTech

Shared and Copied Arrays

Lesson 15 of 48 in Coddy's GDScript for Lua Developers course.

Assigning a Lua table to another name shares the table. Copying its entries into a new table duplicates only the outer storage: nested tables remain shared unless explicitly copied too. GDScript Array and Dictionary assignment also shares containers. Their duplicate() methods make a shallow copy by default; duplicate(true) recursively copies nested arrays and dictionaries, but does not generally clone referenced objects. Choose the depth from the promised ownership contract. A second variable is not proof of independence. The example deliberately changes a shared inner sequence, while the exercise operates on a flat collection.

Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:

Lua file main.lua:

local a = {{1}}
local b = {}
for i, value in ipairs(a) do b[i] = value end
table.insert(b[1], 2)
print(string.format("%d %d", #a[1], #b))

Lua output:

2 1

GDScript file main.gd:

extends Node

func _ready() -> void:
	var a: Array = [[1]]
	var b: Array = a.duplicate()
	b[0].append(2)
	print("%d %d" % [a[0].size(),b.size()])

GDScript output:

2 1
challenge icon

Challenge

Easy

Implement ArrayCopy.extended(values:Array)->Array: return independent outer storage with 9 appended. Do not modify the caller. Elements are integers. The locked driver mutates the returned copy and checks the original.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in array_copy.gd, exercise.gd. The supplied main.gd cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

func contract_ok(data: Array) -> bool:
	var original: Array = [2, 3]
	var copied: Array = ArrayCopy.extended(original)
	if copied != [2,3,9]: return false
	copied[0] = 80
	if original != [2,3]: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz iconTest yourself

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

All lessons in GDScript for Lua Developers

Practice on your own: Online GDScript compiler