Control Flow & Pattern Matching
Don't add or remove elements of an array while iterating over it; iterate over a duplicate() or collect changes and apply them afterward.
11.1 if / elif / else
if hp <= 0:
die()
elif hp < 20:
play_low_health_warning()
else:
pass # 'pass' is an empty statement
var label := "even" if n % 2 == 0 else "odd"11.2 while
var i := 0
while i < 10:
i += 1
if i == 3:
continue
if i == 8:
break
print(i)11.3 for
Don't add or remove elements of an array while iterating over it; iterate over a duplicate() or collect changes and apply them afterward.
for i in 5: # 0..4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
for i in range(10, 0, -1): # 10..1
print(i)
for item in inventory:
print(item)
for key in dict:
print(key, dict[key])
for ch in "abc":
print(ch)
for child in get_children():
child.queue_free()
for i: int in 3: # typed loop variable (4.2+)
print(i)
for enemy: Enemy in enemies:
enemy.alert()11.4 match
match compares a value against patterns; the first matching branch runs (no fall-through in Godot 4).
Pattern guards (4.3+) add an extra condition with when:
42, "text", null, true Constant / enum State.IDLE, MAX Vector2i(0, 0) [1, var y,..] {"key": var v,..}
1, 2, 3 (cannot combine with bindings) var x when x > 10
Godot 3 note: continue inside match used to fall through to the next pattern; this was removed in 4.0.
match command:
"jump":
jump()
"attack", "shoot": # multiple patterns
attack()
_: # wildcard (default)
print("Unknown command")
match typeof(value):
TYPE_INT, TYPE_FLOAT:
print("number")
TYPE_STRING:
print("string")
match position_on_grid:
Vector2i(0, 0):
print("origin")
var other: # binding pattern: captures the value
print("at ", other)
match event_data:
[]:
print("empty array")
[var first, ..]: # array pattern with open ending
print("starts with ", first)
match message:
{"type": "chat", "text": var text}:
show_chat(text)
{"type": "move", "x": var x, "y": var y, ..}: # .. allows extra keys
move_to(Vector2(x, y))match hp:
var h when h <= 0:
die()
var h when h < 25:
show_warning()
_:
pass