Enums in GDScript

Enumerated types (enums) are a special case of sum types. An enum is a type that has a fixed number of possible values, each with a distinct name. Although this language doesn’t have a specific enum type as a distinct language feature, enums can be implemented using existing idioms.

Our enum type `ServerState` has an underlying int type.

```gdscript
enum ServerState {
    STATE_IDLE,
    STATE_CONNECTED,
    STATE_ERROR,
    STATE_RETRYING
}

The possible values for ServerState are defined as constants. Enums in this language do not require a special keyword to generate successive constant values automatically.

By using a dictionary, values of ServerState can be printed out or converted to strings:

var state_name = {
    ServerState.STATE_IDLE: "idle",
    ServerState.STATE_CONNECTED: "connected",
    ServerState.STATE_ERROR: "error",
    ServerState.STATE_RETRYING: "retrying"
}

func state_to_string(ss):
    return state_name[ss]

If we have a value of type int, we cannot pass it to transition - the compiler will complain about type mismatch. This provides some degree of compile-time type safety for enums.

Here’s an example of how our main function and state transition function might look:

func _ready():
    var ns = transition(ServerState.STATE_IDLE)
    print(state_to_string(ns))

    var ns2 = transition(ns)
    print(state_to_string(ns2))

func transition(s):
    match s:
        ServerState.STATE_IDLE:
            return ServerState.STATE_CONNECTED
        ServerState.STATE_CONNECTED, ServerState.STATE_RETRYING:
            # Suppose we check some predicates here to determine the next state...
            return ServerState.STATE_IDLE
        ServerState.STATE_ERROR:
            return ServerState.STATE_ERROR
        _:
            push_error("unknown state: %s" % s)

The transition function emulates a state transition for a server; it takes the existing state and returns a new state.

To run this program, ensure you place the script inside a Node, attach it and run the scene. You should see the output states printed in the console.