Godot 4.2
Static typing checks are turned on in Project Settings (untyped_declaration=error, and so on).
Question
Cannot return enum value from function (in the correct type-consistent manner). It can be returned only as int. So… in the calling context, we have to explicitly cast value (from int to enum back) every time. Is it really so? I didn’t find anything about it in documentation.
You can return an enum value from a function, unless I’m misunderstanding your question.
For example:
enum MyEnum { FOO, BAR, BAZ }
func _get_example_my_enum_value() -> MyEnum:
return MyEnum.FOO
func _process(delta: float) -> void:
# Statically typed as MyEnum
var val: MyEnum = _get_example_my_enum_value()
# But we can also use int:
var i_val: int = _get_example_my_enum_value()
# Both of these are true:
print(val is MyEnum)
print(i_val is MyEnum)
Enums are just ints under the hood. I don’t really know if you can return an enum in GDScript but if you can’t do that, you could treat the int as an enum and compare them to enums like:
GBWD, thank you for the code example. Yes, strange, it works. But I use global enum, it doesn’t work:
File MyEnum.gd
class_name MyEnum
enum { FOO, BAR, BAZ }
File MyNode.gd
func _get_example_my_enum_value() -> MyEnum:
return MyEnum.FOO
func _process(delta: float) -> void:
# Statically typed as MyEnum
var val: MyEnum = _get_example_my_enum_value()
# But we can also use int:
var i_val: int = _get_example_my_enum_value()
# Both of these are true:
print(val is MyEnum)
print(i_val is MyEnum)
So, looks like the problem is global enum, not enum per se. Error message ("Expression is of type “int” so it can’t be of type “MyEnum”) was misleading. )))
Yeah that may be a limitation, since by declaring -> MyEnum the engine expects an object class of MyEnum not an Enum. One way to address this would be to name your Enum like:
class_name MyEnum
enum Name { FOO, BAR, BAZ }
and then you can just declare the return type like