Enums in AngelScript

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. Angelscript doesn’t have an enum type as a distinct language feature, but enums are simple to implement using existing language idioms.

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

```angelscript
enum ServerState {
    StateIdle,
    StateConnected,
    StateError,
    StateRetrying
}

The possible values for ServerState are defined as constants. The special keyword enum generates successive constant values automatically; in this case 0, 1, 2, and so on.

By implementing the Stringer interface, values of ServerState can be printed out or converted to strings.

string stateName(ServerState ss) {
    switch (ss) {
        case StateIdle:      return "idle";
        case StateConnected: return "connected";
        case StateError:     return "error";
        case StateRetrying:  return "retrying";
        default:             return "unknown";
    }
}

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.

void main() {
    ServerState ns = transition(StateIdle);
    print(stateName(ns) + "\n");
    
    ServerState ns2 = transition(ns);
    print(stateName(ns2) + "\n");
}

ServerState transition(ServerState s) {
    switch (s) {
        case StateIdle:
            return StateConnected;
        case StateConnected:
        case StateRetrying:
            return StateIdle;
        case StateError:
            return StateError;
        default:
            throw("unknown state: " + stateName(s));
    }
}

To run this script, you would typically use it within an environment that supports Angelscript. Now that we can run and build basic Angelscript programs, let’s learn more about the language.