User-defined enums

An enumerated type, or enum, is in most programming languages a data type consisting of a list of named integer constants. Megalo doesn't offer enums as a separate type; nonetheless, you can create a list of integer constants grouped under a single name using the enum keyword:

enum my_cool_enum
   value_a
   value_b
   value_c
   value_d
end

global.number[0] = my_cool_enum.value_a

The values in an enum are integer constants, and can be used in any context where an integer constant is accepted.

The syntax for an enum is: the word "enum" followed by a name for the enum, followed by one or more values and then the word "end." Values must be separated by whitespace and can optionally be followed by an equal sign and an integer constant (or alias or other enum value).

If an enum value doesn't have its number specified explicitly, then it will be set to 0 if it's the first value in the enum, or to the previous value plus one.

-- An enum with five values:
enum alphabet a b c d e end
--
-- alphabet.a == 0
-- alphabet.e == 4

enum an_enum_with_explicit_values
   a
   b
   c = 5
   d
   e
end
--
-- an_enum_with_explicit_values.a == 0
-- an_enum_with_explicit_values.b == 1
-- an_enum_with_explicit_values.c == 5
-- an_enum_with_explicit_values.d == 6
-- an_enum_with_explicit_values.e == 7

alias foo = 5
enum some_enum
   bar = foo
end
--
-- some_enum.bar == 5

Enums are block-scoped, but cannot shadow each other.

Functionally speaking, there is no difference between an enum and just having an alias for each individual value. The following pieces of code are identical:

enum chess_piece_type
   none
   pawn
   rook
   bishop
   knight
   queen
   king
end
global.number[0] = chess_piece_type.pawn
alias chess_piece_type_none   = 0
alias chess_piece_type_pawn   = 1
alias chess_piece_type_rook   = 2
alias chess_piece_type_bishop = 3
alias chess_piece_type_knight = 4
alias chess_piece_type_queen  = 5
alias chess_piece_type_king   = 6
global.number[0] = chess_piece_type_pawn