Taking an enum name instead of it's value

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

I created an enum with this code:

enum {
	IDLE,
	RUN,
	JUMP
}

And I’m trying to print the enums names instead of it’s values for easily debug the game, is there a function for this? Thanks.

:bust_in_silhouette: Reply From: MagnusS

According to this reddit post named enums act like dictionaries. So

enum_name.keys()[enum_name.WALK]

should work.

Thanks. I have founded this post too but how could I print the enum from the example below? I have tried without success print("".keys()["".JUMP]) and print(keys()[JUMP]).

enum {
    IDLE,
    RUN,
    JUMP
}

arthurZ | 2019-03-05 01:50

I think that as of 3.1 you have to give the enum a name.

SIsilicon | 2019-03-05 14:20

I’m using godot 3.3.4 and you can still use unnamed enums…

Ghostrix98 | 2021-10-29 11:31

One solution for const enums (unnamed enums) is to create a companion array with the stringnames, i.e.

enum { MOVE_GROUNDED, MOVE_JUMPING, MOVE_FALLING }
const state_names := ["MOVE_GROUNDED", "MOVE_JUMPING", "MOVE_FALLING"]

Then to get an enum name you do:

var my_enum_name: String = state_names[MOVE_GROUNDED]

This only works if the orders match, and therefore the index values match.

Probably best to simplify by using a named enum or just a dictionary, since they are interchangeable:

const STATE := {
	IDLE = "IDLE",
	JUMPING = "JUMPING",
	FALLING = "FALLING",
	ATTACKING = "ATTACKING",
}

print(STATE.IDLE) # "IDLE"

fergicide | 2023-01-22 13:01

This won’t work if you declare enums with custom values:

enum EnumName {YES = -5, NO = 10, NOT_SURE = 100}

The more universal approach would be to query dictionary for the key:

var text_representation: String = EnumName.find_key(particular_value)