Enums

An enum gives a way to give a name to fixed set of possible values. Use an enum when something can only be one of a few known options, like a difficulty level, a direction or a weather type. This makes the code easier to read and avoids mistakes from using magic numbers or strings.

enum Colors {
    Red,
    Green,
    Blue
}

print(Colors.Red) // 0
print(Colors.Green) // 1
print(Colors.Blue) // 2

As seen in above example, the enum is actually a name given to a number. Without the enum, an if statement would look a lot messier:

function GetHexCode(color) {
    switch(color) {
        case 0: // Red
            return "ff0000"
        case 1: // Green
            return "00ff00"
        case 2: // Blue
            return "0000ff"
        default:
            return "ffffff"
    }
}
print(GetHexCode(2)) // 0000ff

You’d really have to add comments to understand and remember what the numbers mean. That’s why we call these magic numbers. It’s a number and it does something. Who knows what the true meaning of the number is, it’s like magic!

So let’s rewrite the bad example with an enum:

function GetHexCode(color) {
    switch(color) {
        case Colors.Red:
            return "ff0000"
        case Colors.Green:
            return "00ff00"
        case Colors.Blue:
            return "0000ff"
        default:
            return "ffffff"
    }
}
print(GetHexCode(Colors.Blue)) // 0000ff

By default, the enums will be assigned a number in sequential order, but it is possible to override this by directly assigning a number to the enum

enum Size {
    Small = 128,
    Medium = 256,
    Large = 512
}

local width = 500;
if (width > Size.Large) {
    print("Large screen width")
} elseif (width > Size.Medium) {
    print("Medium screen width")
} else {
    print("Small screen width)
}

Categories:

Updated: