+4 votes

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.

in Engine by (199 points)

2 Answers

+1 vote

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)

`

by (2,060 points)
+11 votes

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)

by (113 points)
edited by

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 )

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.