(I figured out the solution while writing this up, but I’m posting it since I spent a while searching, and it might be useful to other people who have gotten used to thinking pythonically.)
Godot Version
4.4.1
Question
In GDScript, how do I check if an Array (a sparse one) has a member at a certain arbitrary index? Even arr[0]
throws an exception if nothing has been stored in the array at all, so I can’t check e.g. if arr[0] == null
. Array.has(value)
checks if a value is present, not if something exists at an index; this behavior is the opposite of Dictionary.has(key)
.
Solution
GDScript Arrays have a set size. If index
is greater than or equal to the Array’s current size()
, it will throw an error. To check if an arbitrary index is null/unset, use if index >= arr.size() or arr[index] == null
. Likewise, if you want to set an array index that’s larger than the current size()
, you’ll need to resize()
the array to be larger (although this probably isn’t performant if done naively/often).
You might want to consider a Dictionary instead; I’m not totally sure of the space/time tradeoffs.