Menu
CoddyTech

What is an Enum?

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

Some values can only be one of a few options: a traffic light is red, yellow or green, and a player is idle, running or jumping. You could store the option as a number, with 0 for idle and 1 for running, but then every reader has to remember what each number means:

var state := 1
if state == 1:
	print("Running")

An enum (short for enumeration) gives each option a name. GDScript numbers the names for you, starting at 0:

enum State { IDLE, RUN, JUMP }

Now you write State.RUN instead of 1: the name of the enum, a dot and the option. The code says what it means:

var state := State.RUN
if state == State.RUN:
	print("Running")

An enum is declared at the top level of the script, next to func _ready(): and not inside it. An enum line inside a function is an error that stops the program before it runs:

extends Node

enum State { IDLE, RUN, JUMP }

func _ready():
	var state := State.JUMP
	print(state) # 2

The options are constants, so State.RUN = 5 is an error. A misspelled option such as State.RUNN is reported before the program runs, while a wrong number such as 3 in place of 2 goes unnoticed.

challenge icon

Challenge

Easy

The program reads a whole number from 0 to 3 that stands for the weather. Give the numbers names with an enum and print a piece of advice.

  1. At the top level of the script, declare an enum named Weather with the options SUNNY, CLOUDY, RAINY and SNOWY, in this order.
  2. Compare weather with the enum options (not with the numbers) and print one line:
  • Weather.SUNNY: Wear sunglasses
  • Weather.CLOUDY: Bring a jacket
  • Weather.RAINY: Take an umbrella
  • Weather.SNOWY: Build a snowman

For the input 2, the output is:

Take an umbrella

Try it yourself

extends Node

# Declare the Weather enum here

func _ready():
	var weather := int(OS.read_string_from_stdin())
	# Compare weather with the enum options and print the advice
	pass
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