Quick Help #2 – Array Has an Enum Value or Has It Not?

Today I was implementing a mechanism for saving game state into a file. I am basically using a similar approach as in the official documentation example (https://docs.godotengine.org/en/stable/tutorials/io/saving_games.html). In one of my persistent nodes I noticed something fishy. I was working with an array full of enum values but after loading that particular array my array#has -function always failed. I checked the data with debugger and the array seemed to contain the data exactly as it was before saving. The array had the value but Godot thought it was different.

Prerequisites:

Godot v3.3

Problem:

Array#has function not working after storing an array with enum values into a json file and and restoring the data back into the array.

Here is a simplified version of a persistent node.

enum MyEnum { ONE, TWO, THREE }

var my_array = [ MyEnum.TWO, MyEnum.THREE ]

func save():
    var data = {
        "my_array": my_array
        }
    return data

func has_item(item):
    if my_array.has(item): # this always fails after load
        return true
    return false

Notice the comment marking the failing line in the code.

Resolution:

Use ‘in’ instead of ‘has’. It’s funny that again there was an alternative way of doing the comparison. Take a look at the has_item -function after the change.

func has_item(item):
    if item in my_array: # this always fails after load
        return true
    return false

I suppose the two different approaches should be the same but in my experience they really are not or the has -function hides a bug.

Explanation:

I really don’t know what the issue is as the official documentations states the following.

Returns true if the dictionary has a given key. This is equivalent to using the in operator.

Well it is not. Anyway… I got my code working and I’m happy. I’ll file a bug or ask someone at Godot and move on. Another programming adventure awaits. Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: