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 lockedA 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 10A 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
EasyWrite 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: printCorrect! 0: printYou 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
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