Skip to content

Commit

Permalink
Merge pull request #10095 from Calinou/static-typing-array-typed
Browse files Browse the repository at this point in the history
Clarify restrictions on nested array types in Static typing in GDScript
  • Loading branch information
mhilbrunner authored Oct 17, 2024
2 parents d2e0797 + a878406 commit f293509
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions tutorials/scripting/gdscript/static_typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -198,14 +198,17 @@ To define the type of an ``Array``, enclose the type name in ``[]``.
An array's type applies to ``for`` loop variables, as well as some operators like
``[]``, ``[]=``, and ``+``. Array methods (such as ``push_back``) and other operators
(such as ``==``) are still untyped. Built-in types, native and custom classes,
and enums may be used as element types. Nested array types are not supported.
and enums may be used as element types. Nested array types
(like ``Array[Array[int]]``) are not supported.


::

var scores: Array[int] = [10, 20, 30]
var vehicles: Array[Node] = [$Car, $Plane]
var items: Array[Item] = [Item.new()]
# var arrays: Array[Array] -- disallowed
var array_of_arrays: Array[Array] = [[], []]
# var arrays: Array[Array[int]] -- disallowed

for score in scores:
# score has type `int`
Expand Down Expand Up @@ -407,10 +410,10 @@ that has a script attached with ``class_name MyScript`` and that ``extends
Node2D``. If we have a reference to the object as a ``Node2D`` (for instance,
as it was passed to us by the physics system), we can first check if the
property and method exist and then set and call them if they do::

if "some_property" in node_2d:
node_2d.some_property = 20 # Produces UNSAFE_PROPERTY_ACCESS warning.

if node_2d.has_method("some_function"):
node_2d.some_function() # Produces UNSAFE_METHOD_ACCESS warning.

Expand All @@ -420,7 +423,7 @@ in the referenced type - in this case a ``Node2D``. To make these operations
safe, you can first check if the object is of type ``MyScript`` using the
``is`` keyword and then declare a variable with the type ``MyScript`` on
which you can set its properties and call its methods::

if node_2d is MyScript:
var my_script: MyScript = node_2d
my_script.some_property = 20
Expand All @@ -443,7 +446,7 @@ collision area to show the area's name. Once the object enters the collision
area, the physics system sends a signal with a ``Node2D`` object, and the most
straightforward (but not statically typed) solution to do what we want could
be achieved like this::

func _on_body_entered(body: Node2D) -> void:
body.label.text = name # Produces UNSAFE_PROPERTY_ACCESS warning.

Expand Down

0 comments on commit f293509

Please sign in to comment.