Skip to content

Commit

Permalink
added section on common unsafe operations and their safe counterparts
Browse files Browse the repository at this point in the history
  • Loading branch information
AdriaandeJongh authored and Adriaan de Jongh committed Dec 19, 2023
1 parent 833e2c4 commit 5563b1d
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions tutorials/scripting/gdscript/static_typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,38 @@ if you prefer a more readable and reliable, but more verbose syntax.
``UNSAFE_*`` warnings make unsafe operations more noticeable, than unsafe lines.
Currently, ``UNSAFE_*`` warnings do not cover all cases that unsafe lines cover.

Common unsafe operations and their safe counterparts
----------------------------------------------------

The example below gives an ``UNSAFE_CAST`` warning because ``body.health`` is of
an unknown type::

func _on_body_entered(body: Node2D) -> void:
if "health" in body:
(body.health as Health).take_damage(damage)

This can be made safe using the following syntax, which works because
``Object.get()`` returns ``null`` if the property doesn't exist or is of another
type::

func _on_body_entered(body: Node2D) -> void:
var health: Health = body.get("health")
if health != null:
health.take_damage(damage)

In another example below, we call a method that we know is on the object or
script, but we will still get an ``UNSAFE_METHOD_ACCESS`` warning as the method
is not present in the inferred type (in this case being a Node2D)::

if node_2d.has_method("some_function"):
node_2d.some_function()

To make this operation safe, you can use the following syntax::

var my_script: MyScript = node_2d
if my_script != null:
my_script.some_function()

Cases where you can't specify types
-----------------------------------

Expand Down

0 comments on commit 5563b1d

Please sign in to comment.