Enumeration

Enum

An enumerator is a user defined datatype to assign names to integer constants. This is how to declare an enum:

my_enum :: enum {
  A; 
  B;
  C;
  D;
}

By default, my_enum.A is the value of 0, and the subsequent values for B, C, and D are 1, 2, 3 respectively.

my_enum :: enum {
  A :: 100; 
  B;
  C;
  D;
}

By default, an enum variable is 64 bits wide. To change the default enumerator value, add a specifying integer type in front of the variable.

my_enum :: enum s16 { // This enum is a signed s16
  A;
  B;
  C;
  D;
}

Enum Flags

An enum flag is an enumerator where each individual bit is an individual flag value of true or false. The next value in an enum flag is bit shifted to the right rather than incremented as in enums.

flags :: enum_flags u32 {
  A; // A = 0b00_01
  B; // B = 0b00_10
  C; // C = 0b01_00
  D; // D = 0b10_00
}

Enum flags can either be assigned to or use bit manipulation to set certain values to either true or false. The compiler recognizes when flags are set/unset, and will print out the flags accordingly.

using flags;
print("%\n", A|B); // will print out "A|B"
print("%\n", A|B|C); // will print out "A|B|C"

var := A|B|C|D;
print("%\n", var); // wil print out "A|B|C|D"

Using on Enums

Putting a using on an enum imports the enum into the scope.

Enum :: enum {
  A; B; C; D;
}

using Enum;
e := .A;
if e == {
case .A; print("e=A\n");
case .B; print("e=B\n");
case .C; print("e=C\n");
case .D; print("e=D\n");
}

Enum notes (@)

You can put notes on the declarations if they are full declarations (not just the short form).


Also read: enums official howto.