Static typing of arrays, syntax?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Godotmus

Newbie question… I tried few ways and looks like I did not manage it to work…
Lets say I need Add my objects to an array and wan t manipulate them straight from array. (and not to fetch them temporary to Spatial variable…)

Var my_array:Spatial = # no…?
Var my_array= :Spatial # no…?
Var my_array= [:Spatial] # no…?
Var my_array= as Spatial #???..not tested…

Or is it even possible

:bust_in_silhouette: Reply From: kidscancode

Type hints can’t be used with arrays. The Array container in Godot is a variant container. If you have a particular need for a single-typed array, there are the Pool*Array types.

You can still add Spatial objects to your array, you just can’t specify that the array will only hold Spatials.

Pool array classes:

var my_generic_array: Array
var my_byte_array: PoolByteArray
var my_color_array: PoolColorArray
var my_int_array: PoolIntArray
var my_float_array: PoolRealArray
var my_string_array: PoolStringArray
var my_vector2_array: PoolVector2Array
var my_vector3_array: PoolVector3Array

All classes — Godot Engine (stable) documentation in English

luislodosm | 2020-10-24 17:50

If anyone’s interested, there’s a proposal to support statically typed arrays for Godot 4.0:
Add static type hints for array members · Issue #192 · godotengine/godot-proposals · GitHub

Lightning_A | 2021-02-04 01:04

:bust_in_silhouette: Reply From: andersmmg

A note for anyone finding this now, GDScript 2.0 (in Godot 4.x) now supports typed arrays in the current alphas!

Example:

var my_array: Array[int] = [1, 2, 3]

tested with Godot 4.0 beta 2 – Works.

rockgg | 2022-10-02 02:32

Thank you. This was really helpful.

aNamee | 2023-03-22 23:29

Thank you, this is what I was looking for. Godot 4.0.2 Stable.

Hamzalopode | 2023-05-07 15:40

3 Likes