0 votes

Say I have the following code.

MyEnum { ZERO, ONE, TWO }

func _ready():
    var my_value = MyEnum.ONE
    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?


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):

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?

Godot version v3.3.stable.official
in Engine by (86 points)
edited by

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

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

Now tested and updated my original post.

you diggin deep :) -> 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...

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

Please log in or register to answer this question.

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 Frequently asked questions and 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 [email protected] with your username.