In programming, an array is an ordered collection of values. Depending on the programming language, an array can refer to a list of values that are all of the same type or, as in languages like Python, GDScript, and JavaScript, a list of values of any type.The most important properties of arrays are the following:
They are ordered. The array preserves the order in which you store and add values.
You access values by index. Each value in the array has an associated integer index starting at zero.
Arrays offer great performance when accessing values, iterating over values, and adding and removing values at the end of the array. So, they are the best choice for algorithms that rely on these operations.
To learn more, refer to the array lessons in Learn GDScript From Zero:
Arrays are a staple of programming. In games, you will use them constantly. You can use an array to store a list of players, a list of items in an inventory, a list of nodes, a list of checkpoints, and generally any contiguous list of data.
Optimized arrays
I mentioned how arrays store values of the same type in some languages. This is the case in languages like C and C++ for performance reasons.Having only values of the same type in the array allows the computer to store the data contiguously in memory, making the program more memory-efficient and giving processors potentially faster access to the data.When coding in GDScript, Godot gives you a couple of memory-efficient array types, starting with the prefix "pool". For example, PoolVector2Array is a specialized array containing only Vector2 values. Some APIs in the engine require these pool types for efficiency.
Using type hints with arrays in GDScript
You can use a type hint of the form Array[type] to specify that the array will only contain values of a particular type. For example, Array[int] will only allow integers in the array.Imagine that your game has a party of playable characters that you store in an array, and the corresponding type is PlayableCharacter. You can use the type hint Array[PlayableCharacter] to specify that the array only allows PlayableCharacter objects.
At the time of writing, all GDScript code that uses type hints is more efficient than untyped code because it allows the GDScript interpreter to use optimized code paths. So, in general, you get a performance boost when using type hints, including for arrays.Type hints can make the interpreted GDScript code up to two times faster, depending on the context, compared to using no type hints. It depends a lot on the instructions and the context.