Match Statement
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 30 of 92.
The match statement compares one value against a list of patterns and runs the block of the first pattern that matches. It replaces a long if/elif chain that compares the same variable:
var day := 3
match day:
1:
print("Monday")
2, 3:
print("Midweek")
_:
print("Other day")This prints Midweek.
- Each pattern ends with a colon, and its code is indented one level deeper
- Several values separated by commas share one block:
2, 3: _is the wildcard: it matches any value, so it goes last, likeelse
Only the first matching block runs. GDScript does not fall through to the next pattern, so there is no break to write. If no pattern matches and there is no _, nothing runs.
Patterns can be strings too:
var weapon := "bow"
match weapon:
"sword":
print("Melee")
"bow", "crossbow":
print("Ranged")
_:
print("Unknown")Challenge
EasyThe variable season holds the name of a season. Write a match statement that prints an activity for it:
"Spring": printGo hiking"Summer": printGo swimming"Fall"or"Autumn": printGo apple picking(one pattern with both values)"Winter": printGo skiing- Any other value: print
Stay home
Write all the cases. With season set to "Autumn", the output is:
Go apple pickingTry it yourself
extends Node
func _ready():
var season := "Autumn"
# Write your match statement below
pass
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler