Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading