Godot Version
4.2.2 stable
Question
how do I know the name of enum number?
func _ready():
print(String("{x}").format({x = test[1]}))
enum test{
test1 = 1,
test2 = 2
}
I want output: test1
what ever I try either i get error that function does’t exist or I get number instead of name of enum constant
1 Like
enum’s are not meant to be used like this. If you want this kind of funtionality you would use dictionaries:
var dict: Dictionary = {
"test1" = 1,
"test2" = 2
}
Enums are lists of constants. their names in code gets replaced by their corresponding values when you compile the code → the names dont exist since they only are supposed to help you read the code better
3 Likes
EX74
July 7, 2024, 2:20pm
3
call
test.test2
print(String("{x}").format({x = test.test2}))
2 Likes
EX74
July 7, 2024, 2:48pm
5
I don’t understand what you mean by output is 2
it prints 2 instead of test2
I got the solution and it explained very good thanks
EX74
July 7, 2024, 2:53pm
7
of course, if you want test1 you call test.test1
but since in the example you specified test[1]
is calling the index of the array and it is the second element in the array…
but of course you didn’t have an array, but I still wanted to be precise
It’s important that you solved it
2 Likes
Technically you actually can get the name of the enum by the value:
extends Node2D
enum MyEnum {
VALUE1 = 1,
VALUE2 = 2,
}
func _ready():
# prints 'VALUE1'
print(MyEnum.find_key(1))
EDIT: I’d still be wary of using code that would include magic constants like ‘1’ like this. I’d only advise such a thing if the “1” originated from a place where MyEnum.VALUE1
was returned (an int) and you had another function elsewhere where you wanted the name, ie for debugging output for better readability.
4 Likes
I agree that micalpixel ’s solution more of a solution than what is marked as the solution above.
I posted the following, but is wrong:
Tho I would just do
MyEnum.keys()[1]
but, to each their own!
Edit, I stand corrected
1 Like
That will only work if the values are in plain order without duplicates or gaps, won’t work with:
enum Foo {
Bar = 1
Baz = 3
}
1 Like
they all seem to work now:
func _ready():
var tests = test.test100
print(test.find_key(tests))
enum test{
test278 = 278,
test1 = 1,
test3 = 3,
test2 = 2,
test100 = 100
}
2 Likes
system
Closed
August 6, 2024, 3:42pm
12
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.