Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท GDScript

GDScript Control Flow and Functions: if, for, match

Master GDScript control flow and functions: if/elif/else, for and while loops, match patterns, break and continue, function arguments, defaults, return types, static functions and recursion.

Control flow decides which code runs and how often. Functions let you name a piece of behavior and reuse it. Together they are most of what you write in a Godot game: "if the player pressed jump and is on the floor, jump", "for each enemy, check the distance", "match the state and choose an animation". This lesson covers them all in GDScript 4.

GDScript is read-only on this site. Python stand-ins show the same logic, and the notes call out where Python's syntax differs from GDScript's.

if, elif, else

GDSCRIPT
func grade(score: int) -> String:
    if score >= 90:
        return "A"
    elif score >= 75:
        return "B"
    elif score >= 60:
        return "C"
    else:
        return "Try again"

Conditions do not need parentheses. Combine them with and, or, not. Values are "truthy" in conditions: 0, 0.0, "", [], {} and null are false; most other values are true. Prefer explicit comparisons for clarity: if items.is_empty(): beats if not items:.

A one-line conditional expression:

GDSCRIPT
var label := "alive" if hp > 0 else "dead"

for loops

for iterates over anything iterable: a range, an array, a dictionary, a string, a node's children.

GDSCRIPT
for i in 5:                    # 0, 1, 2, 3, 4
    print(i)

for i in range(2, 10, 3):      # 2, 5, 8   (start, stop, step)
    print(i)

for fruit in ["apple", "pear"]:
    print(fruit)

for key in {"a": 1, "b": 2}:   # iterates keys
    print(key)

for child in get_children():   # every child node
    print(child.name)

To get both index and value, loop over range(items.size()), then use items[i]. Do not remove elements from the array you are looping over; loop over a copy (items.duplicate()) or collect removals and apply them after.

while loops

GDSCRIPT
var n := 10
while n > 1:
    n = n / 2

A while that never ends freezes your game, because Godot cannot draw a frame until the loop finishes. Inside a game, spread repeated work across frames using _process, timers or await, rather than using a long while.

break, continue and pass

GDSCRIPT
for i in 10:
    if i == 3:
        continue       # skip this iteration
    if i == 6:
        break          # leave the loop
    print(i)           # 0 1 2 4 5

func todo() -> void:
    pass               # an empty block

match: pattern matching

match is the best way to choose between many cases, such as states or key names. It is like switch in other languages but stronger.

GDSCRIPT
func describe(value) -> String:
    match value:
        0:
            return "zero"
        1, 2, 3:
            return "small"
        "jump":
            return "an action"
        [var a, var b]:
            return "a pair: %s and %s" % [a, b]
        {"name": var n}:
            return "named " + n
        var x when x is int and x > 100:
            return "big"
        _:
            return "something else"
  • Several values separated by commas match any of them.
  • var name binds the matched value to a new variable.
  • Array and dictionary patterns match shape and contents.
  • _ is the wildcard (default) case. Without it, nothing happens when no case matches.
  • Unlike C, there is no fall-through; each case runs only its own block.

With enums, match pairs well with state machines:

GDSCRIPT
enum State { IDLE, RUN, JUMP }
var state := State.IDLE

func update_animation() -> void:
    match state:
        State.IDLE: $Anim.play("idle")
        State.RUN: $Anim.play("run")
        State.JUMP: $Anim.play("jump")

Functions

GDSCRIPT
func add(a: int, b: int) -> int:
    return a + b

func greet(name: String, greeting := "Hello") -> void:
    print(greeting, ", ", name)

greet("Ada")                # Hello, Ada
greet("Ada", "Welcome")     # Welcome, Ada
  • func name(params) -> ReturnType: is the shape. -> void means it returns nothing.
  • Default arguments (greeting := "Hello") must come after required ones.
  • Typed parameters make errors visible at edit time.
  • A function can return several values via an array or dictionary: return [x, y] then var pair := get_pair().
  • GDScript has no function overloading: one name, one function.
  • Variable-length arguments are written with an array parameter: func sum(numbers: Array[int]).
  • static func belongs to the class: static func clamp_hp(v: int) -> int: and is called as MyClass.clamp_hp(5) when the script has a class_name.

Functions are values too (Callable): var f := add then f.call(1, 2). See Collections and Lambdas.

Recursion

A function can call itself; make sure there is a stopping case:

GDSCRIPT
func factorial(n: int) -> int:
    if n <= 1:
        return 1
    return n * factorial(n - 1)

Stand-in: the same logic in Python

Python lacks match patterns identical to GDScript's, but 3.10+ has match too, and the rest maps one to one. Run it.

Python Stand-in (Python): grade, loops, match and recursion

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

  • Writing = instead of == in a condition (GDScript reports an error).
  • An infinite while loop that freezes the game.
  • Forgetting _: in a match, so unexpected values silently do nothing.
  • Modifying an array while iterating over it.
  • Default arguments before required ones.
  • Using return inside _process to "stop the game". It only ends that call.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is the right way to loop five times in GDScript?

    for i in 5: iterates 0 to 4. GDScript has no C-style for loop.
  2. 2. In match, what does the _ pattern do?

    _ is the wildcard that works as the default case.
  3. 3. Why is a long while loop in _ready dangerous?

    Godot is single-threaded for game logic; a loop that does not return blocks the frame.
  4. 4. Which statement about default arguments is true?

    Optional parameters with defaults go after the required parameters.
  5. 5. How do you skip to the next iteration of a loop?

    continue skips the rest of the body. pass is an empty placeholder.

Summary

  • Use if/elif/else for decisions; for x in collection and for i in n for loops; avoid long while loops in game code.
  • match handles multiple values, bindings, arrays, dictionaries and a _ default.
  • Functions use func name(a: Type, b := default) -> Type:; no overloading; static func belongs to the class.
  • Recursion needs a stopping case; never change a collection while iterating it.

Next: Classes, Inheritance and Exported Variables