Menu
CoddyTech

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: 15

GDScript 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")
Hot

The 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 icon

Challenge

Easy

The program reads an age as an integer into age. Use a match statement with guards to print the age group:

  • 0 to 12: Child
  • 13 to 19: Teenager
  • 20 to 64: Adult
  • 65 to 120: Senior
  • Any other number: Invalid age

Every range includes both ends. For the input 15, the output is:

Teenager

Try it yourself

extends Node

func _ready():
	var age := int(OS.read_string_from_stdin())
	# Print the age group with match and guards
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler