Enums in UnrealScript

Our enum type ServerState has an underlying int type.

enum EServerState
{
    State_Idle,
    State_Connected,
    State_Error,
    State_Retrying
};

class ServerStateEnum extends Object;

var EServerState State;

function Init()
{
    State = State_Idle;
}

function string GetStateName(EServerState State)
{
    switch (State)
    {
        case State_Idle:
            return "idle";
        case State_Connected:
            return "connected";
        case State_Error:
            return "error";
        case State_Retrying:
            return "retrying";
        default:
            return "unknown";
    }
}

function EServerState Transition(EServerState State)
{
    switch (State)
    {
        case State_Idle:
            return State_Connected;
        case State_Connected:
        case State_Retrying:
            // Suppose we check some predicates here to determine the next state...
            return State_Idle;
        case State_Error:
            return State_Error;
        default:
            `log("unknown state: " @ State);
            return State_Error;  // Added a placeholder return to ensure function ends properly
    }
}

function TestEnum()
{
    local EServerState ns, ns2;
    
    ns = Transition(State_Idle);
    `log(GetStateName(ns));
    
    ns2 = Transition(ns);
    `log(GetStateName(ns2));
}

By implementing the GetStateName method, values of EServerState can be printed out or converted to strings.

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.

transition emulates a state transition for a server. It takes the existing state and returns a new state.

Run the TestEnum function to see the state transitions and their corresponding string representations.

class TestServerState extends ServerStateEnum;

function RunTest()
{
    TestEnum();
}

defaultproperties
{
}

To run the code, compile your UnrealScript file and execute it in the Unreal Engine environment.

$ ucc make
$ ucc server dm-deck16?game=yourgame.TestServerState