Match Guards
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 7 of 78.
A guard adds a condition to a pattern. Write when and a condition after the pattern: the pattern matches only if the value fits the pattern and the condition is true. Guards exist since Godot 4.4.
var hp := 15
match hp:
0:
print("Defeated")
var h when h < 20:
print("Low health: ", h)
_:
print("Healthy")Low health: 15GDScript has no range patterns such as 1..10. A binding pattern with a guard does that job: var h when h < 20: matches every value below 20 and names it h.
When a guard is false, match goes on to the next pattern. The patterns are tried from top to bottom, so the order decides which block runs:
var temp := 32
match temp:
var t when t <= 0:
print("Freezing")
var t when t < 15:
print("Cold")
var t when t < 30:
print("Warm")
_:
print("Hot")HotThe second pattern does not need t > 0: a temperature of 0 or below already matched the first one. A guard can use any condition, with other variables and and or or, and it fits any pattern: 5 when hard_mode: matches 5 only while hard_mode is true.
Challenge
EasyThe program reads an age as an integer into age. Use a match statement with guards to print the age group:
0to12:Child13to19:Teenager20to64:Adult65to120:Senior- Any other number:
Invalid age
Every range includes both ends. For the input 15, the output is:
TeenagerTry it yourself
extends Node
func _ready():
var age := int(OS.read_string_from_stdin())
# Print the age group with match and guards
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler