Translate an enum into a String

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By unfa

I have defined an enum like this:

enum AI_STATE {STATE_IDLE, STATE_WANDER, STATE_ALERT, STATE_ATTACK, STATE_DEAD}

I seem to be able to set values with this enum, but how do I translate the enum NAME into a string?

I’d like to be able to print the enum value’s String for debuging, instead of getting Integers.
This is probably very simple, but I can’t figure this out or find an answer anywhere.

1 Like
:bust_in_silhouette: Reply From: estebanmolca

Use ‘str()’ and keys() or values() :

var a=str(AI_STATE.values())
var b=str(AI_STATE.keys())
var c=str(AI_STATE)
var d=var2str(AI_STATE)
var e=var2str(AI_STATE.keys())
print (e)

`

:bust_in_silhouette: Reply From: jluini

If you have an enum value enum_val and you want it as string just do:

ENUM_NAME.keys()[enum_val]

For example:

AI_STATE.keys()[current_state]

That works because keys() returns an array with all the key names.

(Thanks @skarnl for the correction)

Since ENUM.keys() gives back an array with the keys, you can’t just pass in the current_state as a parameter.

Or at least in the most recent version (3.2.1) you can’t anymore - maybe you could previously

If you want to debug you need to do this:

print( AI_STATE.keys()[current_state] )

which is a shorthand for:

var allTheEnumKeys = AI_STATE.keys()
var key_value = allTheEnumKeys[current_state]
print( key_value )

skarnl | 2020-06-16 16:09

Yes @skarnl you are totally right, I was using this and messed up when answering. I edited the answer.

jluini | 2020-06-16 16:30

2 Likes