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) # 2The 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
EasyThe 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.
- At the top level of the script, declare an enum named
Weatherwith the optionsSUNNY,CLOUDY,RAINYandSNOWY, in this order. - Compare
weatherwith the enum options (not with the numbers) and print one line:
Weather.SUNNY:Wear sunglassesWeather.CLOUDY:Bring a jacketWeather.RAINY:Take an umbrellaWeather.SNOWY:Build a snowman
For the input 2, the output is:
Take an umbrellaTry 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
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