Menu

GDScript match: Switch Statements, Patterns and Guards

GDScript's match is its switch statement. Match values, several values at once, the _ wildcard, bound variables, array and dictionary patterns, and when guards.

This page includes runnable editors. Edit, run, and see output instantly.

match compares one value against a list of patterns and runs the first branch that fits. It is GDScript's switch:

jump: Up!
right: Moving sideways
dance: Unknown command
  • Each branch is a pattern followed by : and an indented block.
  • Commas list several values in one branch.
  • _ matches anything, so it works as the default and goes last.
  • There is no break and no fall through: after one branch runs, the match is done.

match with Enums

The most common use is a state machine, with one branch per state of an enum:

300.0 -> IDLE
150.0 -> CHASE
20.0 -> ATTACK
80.0 -> CHASE

Binding a Value with var

var name as a pattern matches anything and stores the value in name for that branch:

zero
something else: 42

Guards with when

Since Godot 4.3, a pattern may end with when and a condition. The branch is taken only if the pattern fits and the condition is true:

100: perfect
93: A
80: B
40: keep practicing

Array Patterns

An array pattern matches an array of the same length, element by element. .. at the end allows any number of extra elements:

no move
walk 3 steps
say hello there
unknown move

Dictionary Patterns

A dictionary pattern checks keys and values. The dictionary must have exactly the listed keys, unless the pattern ends with ..:

+5 gold
a key
nothing useful

Matching on a Type

match compares values, not types. To branch on a type, match on typeof():

number
number
text
list
other

match or if?

Use match when you compare one value against several fixed options, like states, commands or item types. Use if and elif when each branch tests a different condition, such as hp < 10 and then is_on_floor().

Frequently Asked Questions

Does GDScript have a switch statement?

Yes, it is called match. Write match value: and one branch per pattern under it. Unlike C or JavaScript, there is no break: only the first matching branch runs, then the match ends.

What is the default case in a GDScript match?

The wildcard _. Put _: as the last branch and it runs when no other pattern matched.

How do I match several values in one branch?

Separate them with commas: 1, 2, 3: runs for any of the three values.

Can I add a condition to a match branch?

Yes, with a when guard (Godot 4.3 and later): var n when n < 0: matches any value, binds it to n, and only takes the branch when n < 0 is true.

Coddy programming languages illustration

Learn to code with Coddy

Get started