Menu
CoddyTech

Match With Variables

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 6 of 78.

In the Match Statement lesson every pattern was a literal value, like 1: or "bow":. A pattern can also be a constant or a variable: match compares the value with what that name holds when the line runs:

const SECRET := 42
var guess := 42
match guess:
	SECRET:
		print("You found it!")
	_:
		print("Try again")
You found it!

The second new pattern is the binding pattern: var followed by a new name. Like _, it matches any value, and it also stores that value in the new variable, which you can use inside its block:

var level := 5
match level:
	1:
		print("Tutorial")
	var n:
		print("Level %d is locked" % n)
Level 5 is locked

A binding pattern is most useful when you match the result of an expression, which has no name of its own:

var roll_a := 4
var roll_b := 6
match roll_a + roll_b:
	12:
		print("Double six!")
	var total:
		print("You rolled ", total)
You rolled 10

A binding pattern matches everything, so it goes last, like _. Its name must be new: var level: in the second example would be an error, because level already exists. It also cannot share a line with other patterns separated by commas.

match compares types strictly: the string "5" does not match the pattern 5, and neither does the float 5.0. Convert text read from input with int() before you match it against numbers.

challenge icon

Challenge

Easy

Write a number guessing check. The constant SECRET holds the secret number, and the program reads the player's guess as an integer into guess.

Write a match statement on guess with three patterns:

  • The constant SECRET: print Correct!
  • 0: print You gave up.
  • A binding pattern for any other guess: print the guess followed by is not the number.

For the input 17, the output is:

17 is not the number.

Try it yourself

extends Node

func _ready():
	const SECRET := 42
	var guess := int(OS.read_string_from_stdin())
	# Write the match statement below
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