Enums in Match
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 40 of 78.
A match statement can compare a value with enum options. Each pattern is an option, written with its enum name:
enum Light { RED, YELLOW, GREEN }
func _ready():
var light := Light.YELLOW
match light:
Light.RED:
print("Stop")
Light.YELLOW:
print("Slow down")
Light.GREEN:
print("Go")This prints Slow down. As in every match, several options can share one branch, separated by commas, and _ catches everything else:
match light:
Light.RED, Light.YELLOW:
print("Wait")
_:
print("Go")A function that returns a value needs a return on every path. Even when the branches cover every option, GDScript reports Not all code paths return a value unless the match has a _ branch or a return follows it:
func next_light(light: Light) -> Light:
match light:
Light.RED:
return Light.GREEN
Light.GREEN:
return Light.YELLOW
_:
return Light.REDThe parameter and the return type are the enum Light. The function is declared at the top level, like the enum.
Challenge
EasyThe script declares the enum State with the options IDLE, WALK, RUN, JUMP and FALL. Complete the function describe(): it receives a state and returns its description, chosen with a match:
State.IDLE:"Standing still"State.WALKandState.RUN:"Moving"State.JUMPandState.FALL:"In the air"
Use one branch for WALK and RUN, and one for JUMP and FALL. The given code in _ready() reads a line of state names and prints each one with its description. For the input IDLE RUN FALL, the output is:
IDLE: Standing still
RUN: Moving
FALL: In the airTry it yourself
extends Node
enum State { IDLE, WALK, RUN, JUMP, FALL }
func describe(state: State):
# Return the description of the state with a match
pass
func _ready():
var names := OS.read_string_from_stdin().split(" ", false)
for state_name in names:
print(state_name, ": ", describe(State[state_name]))
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