Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท GDScript

GDScript Arrays, Dictionaries, Lambdas and Callables

Work with GDScript collections: typed Arrays, Dictionaries, packed arrays, sorting and filtering, lambdas and Callable, map, filter and reduce, with copy pitfalls explained.

Games are full of lists and lookups: the enemies on screen, the items in a bag, the high-score table, a map from names to scenes. GDScript has two main containers, Array and Dictionary, plus efficient packed arrays and first-class functions called Callables (including anonymous lambdas). This lesson shows how to use all of them and how to avoid the classic "I changed one, but both changed" bug.

GDScript only runs in Godot, so its snippets are read-only. Python stand-ins run the same operations in your browser; the syntax differs slightly and the notes say how.

Arrays

An Array is an ordered, resizable list that can hold any Variant.

GDSCRIPT
var items := ["sword", "shield", "potion"]
items.append("bow")            # add at end
items.push_front("dagger")     # add at start
items.insert(1, "axe")         # insert at index
print(items[0], items[-1])     # first and last
print(items.size(), items.has("bow"), items.find("potion"))
items.erase("shield")          # remove first matching value
var last = items.pop_back()    # remove and return the last
items.remove_at(0)             # remove by index
items.reverse()
items.shuffle()                # randomizes in place
print(items.slice(1, 3))       # a new array of items 1 and 2

Handy functions: is_empty(), clear(), count(v), max(), min(), pick_random(), append_array(other), fill(v), resize(n), and join for strings through ", ".join(items).

Typed arrays

GDSCRIPT
var scores: Array[int] = [10, 20, 30]
var enemies: Array[Node2D] = []

A typed array refuses values of the wrong type, gives better autocomplete and is slightly faster. Use them whenever the contents are all one kind.

Copying: shallow versus deep

Arrays are reference types. Assigning does not copy:

GDSCRIPT
var a := [1, 2, 3]
var b := a            # both names refer to the SAME array
b.append(4)
print(a)              # [1, 2, 3, 4]

var c := a.duplicate()        # a copy (shallow)
var d := a.duplicate(true)    # deep copy: nested arrays and dictionaries copied too

Sorting, filtering and mapping

GDSCRIPT
var nums := [5, 2, 8, 1]
nums.sort()                               # in place: [1, 2, 5, 8]
nums.sort_custom(func(x, y): return x > y)  # descending

var big := nums.filter(func(n): return n > 3)           # [8, 5]
var doubled := nums.map(func(n): return n * 2)
var total := nums.reduce(func(acc, n): return acc + n, 0)
var any_big := nums.any(func(n): return n > 7)
var all_pos := nums.all(func(n): return n > 0)

sort_custom takes a function that returns true when the first argument should come before the second.

Dictionaries

A Dictionary maps keys to values, remembers insertion order, and is perfect for lookups, inventories and settings.

GDSCRIPT
var player := {
    "name": "Ada",
    "hp": 100,
    "items": ["map", "key"],
}
print(player["name"])                   # Ada
print(player.get("mana", 0))            # 0: default when the key is missing
player["hp"] -= 10
player.mana = 50                        # dot syntax works for string keys
if "hp" in player:                      # or player.has("hp")
    print("has hp")
player.erase("mana")

for key in player:
    print(key, " = ", player[key])
for key in player.keys(): pass
for value in player.values(): pass
print(player.size(), player.is_empty())

Reading a missing key with player["xyz"] is an error; use .get(key, default) when it might be absent. Keys can be any Variant (Vector2i(3, 4) is a great key for a grid). Dictionaries can be typed too (Godot 4.4+): var prices: Dictionary[String, int] = {}.

Like arrays, dictionaries are reference types: use .duplicate(true) for a deep copy. Merge with a.merge(b, true) (the second argument says "overwrite existing keys").

JSON in one line

GDSCRIPT
var text := JSON.stringify(player, "  ")     # dictionary to JSON text
var data = JSON.parse_string(text)            # back to a dictionary or null

This is the usual way to read and write save data.

Packed arrays

PackedStringArray, PackedInt32Array, PackedFloat32Array, PackedVector2Array, PackedByteArray and friends store values contiguously. They use much less memory and are faster than a generic Array, and are what the engine uses for meshes, polygons and audio data. Use them for large, uniform data:

GDSCRIPT
var points := PackedVector2Array([Vector2(0, 0), Vector2(10, 5)])
points.append(Vector2(20, 0))

Callables and lambdas

A Callable is a function stored in a variable. You can create one from a method or write an anonymous function (lambda) inline.

GDSCRIPT
func greet(name: String) -> void:
    print("Hi, ", name)

func _ready() -> void:
    var f: Callable = greet            # method as a value
    f.call("Ada")

    var add := func(a: int, b: int) -> int: return a + b     # lambda
    print(add.call(2, 3))              # 5

    var counter := 0
    var inc := func(): counter += 1    # lambdas capture variables...
    inc.call()
    print(counter)                     # ...but a captured int is a copy: still 0

The last lines are a famous trap: a lambda captures local variables by value, so changing a captured int inside the lambda does not change the outer variable. Capture an Array or Dictionary instead (they are references), or store state on the object. Lambdas are great for sort_custom, filter and signal callbacks such as button.pressed.connect(func(): print("clicked")). Method callables also support bind: timer.timeout.connect(spawn_enemy.bind("slime")).

Stand-in: the same operations in Python

Python's lists and dicts are close cousins. Run this to check results.

Python Stand-in (Python): list, dict, map/filter/reduce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Assuming var b := a copies an array.
  • Reading a dictionary key that may not exist without .get().
  • Removing items inside a for loop over the same array.
  • Expecting a lambda to modify a captured int or String.
  • Using a generic Array for a million numbers instead of a packed array.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After var b := a (where a is an Array), what happens when you append to b?

    Arrays are references. Use duplicate() for a copy.
  2. 2. How do you read a Dictionary key that may be missing, with a default?

    get(key, default) returns the default when the key is missing; d[key] errors.
  3. 3. What does sort_custom's function return?

    The comparator returns a bool saying whether a should sort before b.
  4. 4. Why prefer a PackedVector2Array for 100,000 points?

    Packed arrays are contiguous, typed storage with lower memory use and better speed.

Summary

  • Array is an ordered list (use typed arrays); Dictionary is an ordered key-value map; packed arrays hold large uniform data.
  • Both containers are references: use duplicate() (or duplicate(true)) for copies.
  • Use filter, map, reduce, any, all and sort_custom with lambdas.
  • Callables hold functions; lambdas capture variables by value, so state belongs in references or objects.
  • JSON.stringify and JSON.parse_string convert dictionaries to and from text.

Next: The Node Lifecycle: _ready, _process and _physics_process