|
@@ -735,36 +735,44 @@ Static typing
|
|
|
|
|
|
Since Godot 3.1, GDScript supports :ref:`optional static typing<doc_gdscript_static_typing>`.
|
|
|
|
|
|
-Type hints
|
|
|
-~~~~~~~~~~
|
|
|
+Declared Types
|
|
|
+~~~~~~~~~~~~~~
|
|
|
|
|
|
-Place the colon right after the variable's name, without a space, and let the
|
|
|
-GDScript compiler infer the variable's type when possible.
|
|
|
+To declare a variable's type, use ``<variable>: <type>``:
|
|
|
|
|
|
-**Good**:
|
|
|
+::
|
|
|
+
|
|
|
+ var health: int = 0
|
|
|
+
|
|
|
+To declare the return type of a function, use ``-> <type>``:
|
|
|
|
|
|
::
|
|
|
|
|
|
- onready var health_bar: ProgressBar = get_node("UI/LifeBar")
|
|
|
+ func heal(amount: int) -> void:
|
|
|
|
|
|
- var health := 0 # The compiler will use the int type.
|
|
|
+Inferred Types
|
|
|
+~~~~~~~~~~~~~~
|
|
|
|
|
|
-**Bad**:
|
|
|
+In most cases you can let the compiler infer the type, using ``:=``:
|
|
|
|
|
|
::
|
|
|
+ var health := 0 # The compiler will use the int type.
|
|
|
|
|
|
- # The compiler can't infer the exact type and will use Node
|
|
|
- # instead of ProgressBar.
|
|
|
- onready var health_bar := get_node("UI/LifeBar")
|
|
|
+However, in a few cases when context is missing, the compiler falls back to
|
|
|
+the function's return type. For example, ``get_node()`` cannot infer a type
|
|
|
+unless the scene or file of the node is loaded in memory. In this case, you
|
|
|
+should set the type explicitly.
|
|
|
|
|
|
-When you let the compiler infer the type hint, write the colon and equal signs together: ``:=``.
|
|
|
+**Good**:
|
|
|
|
|
|
::
|
|
|
|
|
|
- var health := 0 # The compiler will use the int type.
|
|
|
+ onready var health_bar: ProgressBar = get_node("UI/LifeBar")
|
|
|
|
|
|
-Add a space on either sides of the return type arrow when defining functions.
|
|
|
+**Bad**:
|
|
|
|
|
|
::
|
|
|
|
|
|
- func heal(amount: int) -> void:
|
|
|
+ # The compiler can't infer the exact type and will use Node
|
|
|
+ # instead of ProgressBar.
|
|
|
+ onready var health_bar := get_node("UI/LifeBar")
|