Menu
CoddyTech

Enum Values

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

Every enum option is an int, so you can compare options and calculate with them:

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

func _ready():
	print(Day.FRIDAY) # 4
	print(Day.SATURDAY > Day.FRIDAY) # true
	print(Day.FRIDAY + 1) # 5

The enum itself works like a dictionary from names to values. keys() returns the names in order, values() the values, and size() the number of options:

print(Day.keys()) # ["MONDAY", "TUESDAY", ..., "SUNDAY"]
print(Day.size()) # 7

To print the name of a value, index keys() with it. This works when the options have the default values 0, 1, 2... For an enum with chosen values, use find_key(), which returns the name of a value:

var today := Day.SATURDAY
print(Day.keys()[today]) # SATURDAY

With enum Coin { COPPER = 1, SILVER = 10 } at the top level, Coin.keys()[10] is out of range, while find_key() works:

print(Coin.find_key(10)) # SILVER

To go the other way, from a name stored as text to its value, use square brackets. Check the name with has() first: a name that is not in the enum is an error.

var text := "FRIDAY"
if Day.has(text):
	print(Day[text]) # 4

for day_name in Day: loops over the names, like a loop over a dictionary.

challenge icon

Challenge

Easy

The script declares the enum Day, from MONDAY to SUNDAY. The program reads two lines: the name of a day in capitals and a number of days (a whole number, 0 or more).

Print two lines:

  1. The name, has the value and the value of that day in the enum
  2. In, the number, days: and the name of the day that many days later

After SUNDAY the week starts again at MONDAY. For the inputs FRIDAY and 3, the output is:

FRIDAY has the value 4
In 3 days: MONDAY

Try it yourself

extends Node

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

func _ready():
	var day_name := OS.read_string_from_stdin()
	var days := int(OS.read_string_from_stdin())
	# Print the value of the day and the day after that many days
	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