How to convert a string to enum in Godot?
Asked Answered
M

1

7

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?

Metametabel answered 4/12, 2021 at 16:5 Comment(0)
S
10

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.

Suffering answered 4/12, 2021 at 16:24 Comment(1)
This doesn't seem to work in Godot 4.2+ for Enum entries with a custom Integer value, like: ``` enum Facing { LEFT = -1, RIGHT = 1 } print("Facing: ", _facing, " Facing.enum = %s" % [Facing.keys()[_facing]]) ``` The _facing property correctly switches between -1 and 1, but the Keys lookup always returns RIGHT (I'm guessing because the ordinals are 0 and 1).Plagal

© 2022 - 2024 — McMap. All rights reserved.