Menu
CoddyTech

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, like else

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 icon

Challenge

Easy

The variable season holds the name of a season. Write a match statement that prints an activity for it:

  • "Spring": print Go hiking
  • "Summer": print Go swimming
  • "Fall" or "Autumn": print Go apple picking (one pattern with both values)
  • "Winter": print Go skiing
  • Any other value: print Stay home

Write all the cases. With season set to "Autumn", the output is:

Go apple picking

Try it yourself

extends Node

func _ready():
	var season := "Autumn"
	# Write your match statement below
	pass
quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online GDScript compiler