Skip to content

Commit 8a22a6d

Browse files
authored
Merge pull request godotengine#7507 from dalexeev/gds-var-init-order
GDScript: Document variable initialization order
2 parents 27d9837 + c3322d8 commit 8a22a6d

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

tutorials/scripting/gdscript/gdscript_basics.rst

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -976,7 +976,7 @@ value upon initialization.
976976
var a # Data type is 'null' by default.
977977
var b = 5
978978
var c = 3.8
979-
var d = b + c # Variables are always initialized in order.
979+
var d = b + c # Variables are always initialized in direct order (see below).
980980

981981
Variables can optionally have a type specification. When a type is specified,
982982
the variable will be forced to have always that same type, and trying to assign
@@ -1018,6 +1018,49 @@ Valid types are:
10181018
You can turn off this check, or make it only a warning, by changing it in
10191019
the project settings. See :ref:`doc_gdscript_warning_system` for details.
10201020

1021+
Initialization order
1022+
^^^^^^^^^^^^^^^^^^^^
1023+
1024+
Member variables are initialized in the following order:
1025+
1026+
1. Depending on the variable's static type, the variable is either ``null``
1027+
(untyped variables and objects) or has a default value of the type
1028+
(``0`` for ``int``, ``false`` for ``bool``, etc.).
1029+
2. The specified values are assigned in the order of the variables in the script,
1030+
from top to bottom.
1031+
- *(Only for ``Node``-derived classes)* If the ``@onready`` annotation is applied to a variable, its initialization is deferred to step 5.
1032+
3. If defined, the ``_init()`` method is called.
1033+
4. When instantiating scenes and resources, the exported values are assigned.
1034+
5. *(Only for ``Node``-derived classes)* ``@onready`` variables are initialized.
1035+
6. *(Only for ``Node``-derived classes)* If defined, the ``_ready()`` method is called.
1036+
1037+
.. warning::
1038+
1039+
You can specify a complex expression as a variable initializer, including function calls.
1040+
Make sure the variables are initialized in the correct order, otherwise your values
1041+
may be overwritten. For example::
1042+
1043+
var a: int = proxy("a", 1)
1044+
var b: int = proxy("b", 2)
1045+
var _data: Dictionary = {}
1046+
1047+
func proxy(key: String, value: int):
1048+
_data[key] = value
1049+
print(_data)
1050+
return value
1051+
1052+
func _init() -> void:
1053+
print(_data)
1054+
1055+
Will print::
1056+
1057+
{ "a": 1 }
1058+
{ "a": 1, "b": 2 }
1059+
{ }
1060+
1061+
To fix this, move the ``_data`` variable definition above the ``a`` definition
1062+
or remove the empty dictionary assignment (``= {}``).
1063+
10211064
Static variables
10221065
^^^^^^^^^^^^^^^^
10231066

0 commit comments

Comments
 (0)