Why is enum value not equal to int equivalent?

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

Say I have the following code.

MyEnum { ZERO, ONE, TWO }

func _ready():
    var my_value = MyEnum.ONE
    _save_enum_to_file(my_value)
    var loaded_value = _load_value_from_file()
    assert(loaded_value == MyEnum.ONE, "not the same")

When executed the assertion will fail. I am aware I can get the correct enum value like this:

var loaded_value = MyEnum.values()[_load_value_from_file())

But this feels a bit odd.

My first question is why is the loaded_value with value 1 different from MyEnum.ONE (which is basically 1)? (In other words: why is 1 not equal to 1?)

Secondly, is there a proper way to handle the situation when saving/loading?

UPDATE:

Ok. I tried what frankiezafe suggested. Well at least sort of. It appears that when I put my value into a dictionary {"my_value": my_value}, then save it into a file as json and finally load the file and parse the json I get the value back as float. BUT as frankiezafe suggested I tried casting like this:

var loaded_value = _load_value_from_file() as int 

That obviously works when I am 100% sure the value is an int.

Also my original example was not correct. The assert in my case would work perfectly but for instance the following code would not work.

if MyEnum.values().has(loaded_value):
	print("SUCCESS")

So now I have another question: Why is float value 1 equal to enum value 1 when asserting but not equal when the comparison is done with the has function?

Not certain, but any uncasted variable in gdscript is a ‘Variant’ (see here), not an int. This might be the issue

  • you could test MyEnum.ONE and loaded_value with if ... is int

  • maybe if you cast loaded_value to int with var loaded_value:int it could avoid the issue

frankiezafe | 2021-06-23 12:14

Hmmm… Interesting point. I will try that and get back.

StopNot | 2021-06-23 17:39

Now tested and updated my original post.

StopNot | 2021-06-23 19:53

you diggin deep :slight_smile: → i guess you’ll have a consistent answer if you analyse the c++ code being the ‘.has’ method, that might use a stronger type testing then assert…

frankiezafe | 2021-06-24 09:22

yeah, it’s just that this has been bothering me for a while now… maybe I’ll dig into the c++ code at some point but for now it’s enough to know how to get my code running smoothly… anyway, you pointed me into the right direction so thanks for that

StopNot | 2021-06-24 10:34