Search code examples
enumsgodotgdscript

How to convert a string to enum in Godot?


Using Godot 3.4, I have an enum setup as:

enum {
    STRENGTH, DEXTERITY, CONSTITUTION, INTELLIGENCE, WISDOM, CHARISMA
}

And I would like to be able to make the string "STRENGTH" return the enum value (0). I would like the below code to print the first item in the array however it currently presents an error that STRENGTH is an invalid get index.

boost = "STRENGTH"
print(array[boost])

Am I doing something wrong or is there a function to turn a string into something that can be recognised as an enum?


Solution

  • First of all, your enum needs a name. Without the name, the enum is just a fancy way to make a series of constants. For the purposes of this answer, I'll use MyEnum, like this:

    enum MyEnum {
        STRENGTH, DEXTERITY, CONSTITUTION, INTELLIGENCE, WISDOM, CHARISMA
    }
    

    Now, we can refer to the enum and ask it about its elements. In particular, we can figure out what is the value associated with a name like this:

        var boost = "DEXTERITY"
        print("Value of ", boost, ": ", MyEnum.get(boost))
    

    That should print:

    Value of DEXTERITY: 1
    

    By the way, if you want to get the name from the value, you can do this:

        var value = MyEnum.DEXTERITY
        print("Name of ", value, ": ", MyEnum.keys()[value])
    

    That should print:

    Name of 1: DEXTERITY
    

    What you are getting is just a regular dictionary preset with the contents of the enum. So, we can ask it about all the values:

        for boost in MyEnum:
            print(boost)
    

    Which will print:

    STRENGTH
    DEXTERITY
    CONSTITUTION
    INTELLIGENCE
    WISDOM
    CHARISMA
    

    And we can also ask it if it has a particular one, for example print(MyEnum.has("ENDURANCE")) prints False.

    And yes you could edit the dictionary. It is just a dictionary you get initialized with the values of the enum.