Search code examples
gdscript

Enums and static typing


I have declared an enum in some gdscript code.

Then, I want to declare some variables to be of that type of enum.

Is this possible. I know GDScript allows to declare a static type of a var. MEvery language I have used allows you to treat an enum as a var.

The following code produces the following error for me...

enum XDir {
    None,
    Left,
    Right
}

enum YDir {
    None,
    Up,
    Down
}

var x_dir : XDir
var y_dir : YDir

Parser Error: Identifier 'XDir' is not a valid type (not a script or class), or could not be found on base 'self'.


Solution

  • This is not possible yet. Enums in GDScript are syntactic sugar for constant dictionaries and are not actual types.

    You'll have to use int as the type until enums are made into real types.

    Do note that you can still give enums to export like

    export(XDir) var x_dir: int
    

    To enforce an enum value at runtime you can do:

    assert(XDir.has(x_dir))