Shared and Copied Arrays
Lesson 15 of 48 in Coddy's GDScript for C# Developers course.
Assigning a C# List reference and assigning a GDScript Array both share the container. A C# list copy constructor and GDScript duplicate create shallow outer copies: nested containers remain shared. duplicate(true) recursively copies nested Arrays and Dictionaries, but ordinary object references are not automatically replaced by new class instances. Choose copying depth from the API ownership promise. The sample intentionally exposes nested sharing, while the task works with flat integers and requires independent outer storage.
Complete C# comparison. Compile all listed C# files together; Program.Main is the entry point.
C# file Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program {
public static void Main() {
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var a=new List<List<int>>{new List<int>{1}};var b=new List<List<int>>(a);b[0].Add(2);Console.WriteLine("{0} {1}",a[0].Count,b.Count);
}
}C# output:
2 1GDScript example 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 1Challenge
EasyImplement 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. main.gd holds the supplied input/output code and 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))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for C# Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command Count3Collection Ownership
Array OperationsTyped ArraysShared and Copied ArraysDictionary PresenceDictionary TraversalRecap: Word FrequenciesPractice on your own: Online GDScript compiler