Arrays, Dictionaries & Strings
Games are full of lists and lookups: an inventory, the enemies in a wave, high scores, dialogue lines, tile coordinates. GDScript has two general containers, Array and Dictionary, a set of fast packed arrays for numbers and vectors, and a rich String type. All of them are built in; there is nothing to import.
Arrays
extends SceneTree
func _init():
var loot := ["sword", "potion", "shield"]
loot.append("potion")
loot.insert(1, "bow")
print(loot, " size=", loot.size(), " potions=", loot.count("potion"))
print(loot.find("shield"), " ", loot.has("axe"), " ", loot[0], " ", loot[-1])
print("popped ", loot.pop_back(), " and ", loot.pop_front())
loot.erase("bow") # removes the first match
print(loot)
var nums: Array[int] = [5, 3, 9, 1] # a typed array: only ints allowed
nums.sort()
print(nums, " min=", nums.min(), " max=", nums.max(), " slice=", nums.slice(1, 3))
print(nums.map(func(n): return n * 10))
print(nums.filter(func(n): return n > 2))
print(nums.reduce(func(total, n): return total + n, 0))
print(nums.any(func(n): return n > 8), " ", nums.all(func(n): return n > 0))
quit()["sword", "bow", "potion", "shield", "potion"] size=5 potions=2
3 false sword potion
popped potion and sword
["potion", "shield"]
[1, 3, 5, 9] min=1 max=9 slice=[3, 5]
[10, 30, 50, 90]
[3, 5, 9]
18
true true
- Negative indices count from the end (
loot[-1]). An index out of range is a runtime error, so checksize()first. Array[int],Array[Node2D],Array[String]are typed arrays. They reject wrong values and make loops faster; use them for every array whose element type you know.map,filter,reduce,any,alltake lambdas and return new arrays.sort()sorts in place.
Sorting by a key, and references vs copies
extends SceneTree
func _init():
var enemies := [
{"name": "bat", "hp": 3},
{"name": "orc", "hp": 12},
{"name": "slime", "hp": 5},
]
enemies.sort_custom(func(a, b): return a.hp > b.hp) # true when a goes first
print(enemies.map(func(e): return e.name))
var a := [1, 2]
var b := a # the same array, not a copy
b.append(3)
var c := a.duplicate() # a shallow copy
c.append(4)
print("a=", a, " c=", c)
var grid := []
for y in 2:
var row := []
for x in 3:
row.append(x + y * 3)
grid.append(row)
var shallow := grid.duplicate()
var deep := grid.duplicate(true)
grid[0][0] = 99
print("shallow sees ", shallow[0][0], ", deep sees ", deep[0][0])
quit()["orc", "slime", "bat"]
a=[1, 2, 3] c=[1, 2, 3, 4]
shallow sees 99, deep sees 0
Arrays and dictionaries are passed by reference. Assigning one to another variable, or passing it to a function, shares it. duplicate() copies the outer container, duplicate(true) copies nested arrays and dictionaries too. Forgetting this is how "resetting the level also reset the high score table" bugs happen.
Dictionaries
A Dictionary maps keys to values and keeps insertion order. Keys are usually strings or StringNames, but any value works (Vector2i keys are perfect for grids):
extends SceneTree
func _init():
var inventory := {"gold": 10, "keys": 1}
inventory["gems"] = 2
inventory.gold += 5 # dot syntax works for string keys
print(inventory, " size=", inventory.size())
print(inventory.get("arrows", 0), " ", inventory.has("keys"), " ", "keys" in inventory)
for item in inventory:
print(item, " = ", inventory[item])
inventory.erase("keys")
print(inventory.keys(), " ", inventory.values())
var walls := {} # a set of grid cells
walls[Vector2i(2, 3)] = true
walls[Vector2i(4, 3)] = true
print(Vector2i(2, 3) in walls, " ", Vector2i(3, 3) in walls)
var scores: Dictionary[String, int] = {"ada": 3} # typed dictionary (Godot 4.4+)
scores["linus"] = 7
var best: int = scores["linus"] # indexing returns a Variant, so declare the type
print(scores, " best=", best)
quit(){ "gold": 15, "keys": 1, "gems": 2 } size=3
0 true true
gold = 15
keys = 1
gems = 2
["gold", "gems"] [15, 2]
true false
{ "ada": 3, "linus": 7 } best=7
- Reading a missing key with
dict["x"]is an error;dict.get("x", default)returns the default instead. for key in dictloops over keys in insertion order.var best := scores["linus"]does not compile: indexing a dictionary returns aVariant, and:=can't infer a type from it. Write the type (var best: int = ...) or cast it (scores["linus"] as int). The same applies to most values read from JSON.
Packed arrays
PackedInt32Array, PackedFloat32Array, PackedVector2Array, PackedStringArray, PackedByteArray and friends store one type contiguously in memory. They use far less memory than Array, and engine APIs use them for polygons, meshes, lines and file bytes. Between your own variables they are shared like Array, but a node property such as Line2D.points hands you a copy, so changing it in place does nothing. Read, modify, assign back:
var outline := PackedVector2Array([Vector2(0, 0), Vector2(32, 0), Vector2(32, 32)])
$CollisionPolygon2D.polygon = outline
$Trail.points.append(Vector2(10, 10)) # no effect: appends to a temporary copy
var pts: PackedVector2Array = $Trail.points
pts.append(Vector2(10, 10))
$Trail.points = pts # works (or use Line2D.add_point())Strings
extends SceneTree
func _init():
var title := " Coin Climber "
var clean := title.strip_edges()
print("[", clean, "] ", clean.to_upper(), " ", clean.length())
print(clean.begins_with("Coin"), " ", clean.find("Climb"), " ", clean.substr(5, 3))
print("a,b,,c".split(","), " ", "a,b,,c".split(",", false))
print(", ".join(["sword", "shield"]))
print("level_03".trim_prefix("level_").to_int() + 1, " ", str(7).pad_zeros(3))
# Formatting: the % operator, like C's printf
print("%s scored %d points in %.1f s" % ["Ada", 1200, 42.25])
print("[%5d] [%-5d] [%05.1f]" % [42, 42, 3.14159])
# or named placeholders
print("Hello {name}, you have {n} coins".format({"name": "Ada", "n": 12}))
var action := &"jump" # a StringName: an interned string, fast to compare
print(action == "jump", " ", type_string(typeof(action)))
quit()[Coin Climber] COIN CLIMBER 12
true 5 Cli
["a", "b", "", "c"] ["a", "b", "c"]
sword, shield
4 007
Ada scored 1200 points in 42.2 s
[ 42] [42 ] [003.1]
Hello Ada, you have 12 coins
true StringName
- Strings are values (copied, never shared) and immutable in practice: every method returns a new string.
%takes a single value or an array.%dintegers,%f/%.2ffloats,%sanything,%5dpads with spaces,%05.1fwith zeros.%.1frounds42.25to42.2, not42.3: 42.25 has no exact binary representation, and C-style formatting rounds the stored value. When the last digit matters (prices, scores), work in integers.StringName(&"jump") is used for action names, signal names, animation names and node names. Comparing twoStringNames is a pointer comparison, so the engine uses them everywhere. You can pass a normalStringwhere aStringNameis expected; it converts automatically.
Choosing a container
| You need | Use |
|---|---|
| an ordered list of objects | Array[Type] |
| a lookup by name or id | Dictionary (typed if possible) |
| a set of things | Dictionary with true values, or a Array + has() for small lists |
| a grid of cells | Dictionary with Vector2i keys (sparse) or a flat Array with index = y * width + x (dense) |
| numbers or vectors for the engine | a Packed*Array |
Test yourself
var b := a where a is an Array, then b.append(3). What happens to a?
- Nothing,
bis a copy aalso gets 3: arrays are shared by reference- An error
abecomes empty
Why does var hp := stats["hp"] fail to compile when stats is an untyped Dictionary?
- Dictionaries can't hold ints
- The value is a Variant, so
:=can't infer a static type; writevar hp: int = stats["hp"] hpis a reserved word- Keys must be StringNames
How do you read a dictionary key that may be missing without an error?
dict[key]dict.get(key, default)dict.key?try: dict[key]