Extreme Noob Question Arrays/Looping

Godot Version

4.2.2

Question

I am trying to make an array that stores a bool value for each item.

So I tried this to initialize:

@export var map_components: Array[bool];

and this to populate each of the four vars this:

for n in 4:
		map_components[n] = false;

And this resulted in an error and I cannot see it.

Fresh eyes on what I am doing wrong here would be greatly appreciated I have never done a loop or made an array before in Godot.

Regards.

Your export array would have to have four elements inside of it. Check the inespector see if it has four blank/false items.

You could also use .resize()

Not sure if that for loop syntax works. Prefer range(4)

# could be declared without export like so
var map_components: Array[bool] = []

map_components.resize(4)
for n in range(4):
    map_components[n] = false
1 Like

That should definitely work, but even if the array size is larger than 4, the array will only access the first 4 elements.

If you are adding values at the end of the array (like you seem to be doing), you can use append(value). No need to resize.

for n in 4:
	map_components.append(false)
2 Likes

Oh boy, I had that all wrong :astonished:. Thanks for putting me straight. I’ll keep everything you said in mind :man_bowing:.

Not gonna lie, I was looking at going in that direction if I needed to, but, I am much more comfortable with what @gertkeno did. I now have it working with what he did.

Thankyou to all who replied it is appreciated :grinning:.

2 Likes

If you want to go really effecient, you can notice that an array of bool is the same as a binary number

1001 vs true, false, false, true

bitwise operators let you use ints as bool arrays, and so does @export_flags. this lets you create properties in the inspector like collision layer/mask where you can select multiple true/false values.

@export_flags("Fire", "Water", "Earth", "Wind") var spell_elements = 0

func has_water() -> bool:
    # binary is flipped compared to the flag names
    return spell_elements & 0b0010 != 0

func has_wind() -> bool:
    return spell_elements & 0b1000 != 0

Something to try out, if your use case can leverage it.

My brain hurts :rofl:.

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.