Enums in Scilab

Our enum type ServerState has an underlying int type.

// Scilab does not have an enum type, but we can mimic the behavior using constants.

ServerStateIdle = 0;
ServerStateConnected = 1;
ServerStateError = 2;
ServerStateRetrying = 3;

The possible values for ServerState are defined as constants. Scilab uses predefined values to represent these states.

By implementing a simple map function, values of ServerState can be printed out or converted to strings.

function name = getStateName(state)
  select state
    case ServerStateIdle then
      name = "idle";
    case ServerStateConnected then
      name = "connected";
    case ServerStateError then
      name = "error";
    case ServerStateRetrying then
      name = "retrying";
    else
      name = "unknown";
  end
endfunction

If we have a value of type int, we use predefined mappings, which provides some degree of compile-time type safety.

function main()
  ns = transition(ServerStateIdle);
  disp(getStateName(ns));
  
  ns2 = transition(ns);
  disp(getStateName(ns2));
endfunction

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

function newState = transition(state)
  select state
    case ServerStateIdle then
      newState = ServerStateConnected;
    
    case ServerStateConnected then
      newState = ServerStateIdle;

    case ServerStateRetrying then
      newState = ServerStateIdle;

    case ServerStateError then
      newState = ServerStateError;

    else
      error("Unknown state: " + string(state));
  end
endfunction

main();

Running the Scilab script emulates the behavior as described.

--> main();
// Output:
// connected
// idle

With this approach, you have a basic implementation of an enum-like feature using constants in Scilab.