Menu
CoddyTech

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.RED

The parameter and the return type are the enum Light. The function is declared at the top level, like the enum.

challenge icon

Challenge

Easy

The 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.WALK and State.RUN: "Moving"
  • State.JUMP and State.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 air

Try 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]))
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