Menu
CoddyTech

Named Integer States

Lesson 37 of 48 in Coddy's GDScript for Lua Developers course.

Lua often represents named states as fields in a table. Those fields are ordinary mutable entries unless an application enforces another policy. GDScript enums declare named integer constants; omitted values increase from the preceding value. Neither a table of names nor an integer API proves that external input is an allowed state. Validate membership before selecting behavior. A named enum can group constants inside a script class. The examples use two modes beginning at four, while the task's state machine uses its own declared codes and transition contract.

Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:

Lua file main.lua:

local Mode = {LOW = 4, HIGH = 5}
print(Mode.HIGH)

Lua output:

5

GDScript file demo_modes.gd:

class_name DemoModes
extends RefCounted
enum Mode { LOW = 4, HIGH }

GDScript file main.gd:

extends Node

func _ready() -> void:
	print(DemoModes.Mode.HIGH)

GDScript output:

5
challenge icon

Challenge

Easy

Define JobState enum Phase {WAITING=0,RUNNING=1,DONE=2}. Static advance(value:int)->int advances 0 to 1 and 1 to 2, leaves 2 at 2, and returns -1 for every other integer.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in job_state.gd, exercise.gd. The supplied main.gd cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

func contract_ok(data: Array) -> bool:
	if JobState.Phase.WAITING != 0 or JobState.Phase.RUNNING != 1 or JobState.Phase.DONE != 2 or JobState.advance(9) != -1 or JobState.advance(1) != 2: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for Lua Developers

Practice on your own: Online GDScript compiler