gdscript_basics.rst 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. .. _doc_gdscript:
  2. GDScript basics
  3. ===============
  4. Introduction
  5. ------------
  6. *GDScript* is a high-level, dynamically typed programming language used to
  7. create content. It uses a syntax similar to
  8. `Python <https://en.wikipedia.org/wiki/Python_%28programming_language%29>`_
  9. (blocks are indent-based and many keywords are similar). Its goal is
  10. to be optimized for and tightly integrated with Godot Engine, allowing great
  11. flexibility for content creation and integration.
  12. History
  13. ~~~~~~~
  14. .. note::
  15. Documentation about GDScript's history has been moved to the
  16. :ref:`Frequently Asked Questions <doc_faq_what_is_gdscript>`.
  17. Example of GDScript
  18. ~~~~~~~~~~~~~~~~~~~
  19. Some people can learn better by taking a look at the syntax, so
  20. here's a simple example of how GDScript looks.
  21. ::
  22. # A file is a class!
  23. # Inheritance
  24. extends BaseClass
  25. # (optional) class definition with a custom icon
  26. class_name MyClass, "res://path/to/optional/icon.svg"
  27. # Member variables
  28. var a = 5
  29. var s = "Hello"
  30. var arr = [1, 2, 3]
  31. var dict = {"key": "value", 2: 3}
  32. var typed_var: int
  33. var inferred_type := "String"
  34. # Constants
  35. const ANSWER = 42
  36. const THE_NAME = "Charly"
  37. # Enums
  38. enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
  39. enum Named {THING_1, THING_2, ANOTHER_THING = -1}
  40. # Built-in vector types
  41. var v2 = Vector2(1, 2)
  42. var v3 = Vector3(1, 2, 3)
  43. # Function
  44. func some_function(param1, param2):
  45. var local_var = 5
  46. if param1 < local_var:
  47. print(param1)
  48. elif param2 > 5:
  49. print(param2)
  50. else:
  51. print("Fail!")
  52. for i in range(20):
  53. print(i)
  54. while param2 != 0:
  55. param2 -= 1
  56. var local_var2 = param1 + 3
  57. return local_var2
  58. # Functions override functions with the same name on the base/parent class.
  59. # If you still want to call them, use '.' (like 'super' in other languages).
  60. func something(p1, p2):
  61. .something(p1, p2)
  62. # Inner class
  63. class Something:
  64. var a = 10
  65. # Constructor
  66. func _init():
  67. print("Constructed!")
  68. var lv = Something.new()
  69. print(lv.a)
  70. If you have previous experience with statically typed languages such as
  71. C, C++, or C# but never used a dynamically typed one before, it is advised you
  72. read this tutorial: :ref:`doc_gdscript_more_efficiently`.
  73. Language
  74. --------
  75. In the following, an overview is given to GDScript. Details, such as which
  76. methods are available to arrays or other objects, should be looked up in
  77. the linked class descriptions.
  78. Identifiers
  79. ~~~~~~~~~~~
  80. Any string that restricts itself to alphabetic characters (``a`` to
  81. ``z`` and ``A`` to ``Z``), digits (``0`` to ``9``) and ``_`` qualifies
  82. as an identifier. Additionally, identifiers must not begin with a digit.
  83. Identifiers are case-sensitive (``foo`` is different from ``FOO``).
  84. Keywords
  85. ~~~~~~~~
  86. The following is the list of keywords supported by the language. Since
  87. keywords are reserved words (tokens), they can't be used as identifiers.
  88. Operators (like ``in``, ``not``, ``and`` or ``or``) and names of built-in types
  89. as listed in the following sections are also reserved.
  90. Keywords are defined in the `GDScript tokenizer <https://github.com/godotengine/godot/blob/master/modules/gdscript/gdscript_tokenizer.cpp>`_
  91. in case you want to take a look under the hood.
  92. +------------+---------------------------------------------------------------------------------------------------------------+
  93. | Keyword | Description |
  94. +============+===============================================================================================================+
  95. | if | See `if/else/elif`_. |
  96. +------------+---------------------------------------------------------------------------------------------------------------+
  97. | elif | See `if/else/elif`_. |
  98. +------------+---------------------------------------------------------------------------------------------------------------+
  99. | else | See `if/else/elif`_. |
  100. +------------+---------------------------------------------------------------------------------------------------------------+
  101. | for | See for_. |
  102. +------------+---------------------------------------------------------------------------------------------------------------+
  103. | while | See while_. |
  104. +------------+---------------------------------------------------------------------------------------------------------------+
  105. | match | See match_. |
  106. +------------+---------------------------------------------------------------------------------------------------------------+
  107. | break | Exits the execution of the current ``for`` or ``while`` loop. |
  108. +------------+---------------------------------------------------------------------------------------------------------------+
  109. | continue | Immediately skips to the next iteration of the ``for`` or ``while`` loop. |
  110. +------------+---------------------------------------------------------------------------------------------------------------+
  111. | pass | Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions. |
  112. +------------+---------------------------------------------------------------------------------------------------------------+
  113. | return | Returns a value from a function. |
  114. +------------+---------------------------------------------------------------------------------------------------------------+
  115. | class | Defines a class. |
  116. +------------+---------------------------------------------------------------------------------------------------------------+
  117. | extends | Defines what class to extend with the current class. |
  118. +------------+---------------------------------------------------------------------------------------------------------------+
  119. | is | Tests whether a variable extends a given class, or is of a given built-in type. |
  120. +------------+---------------------------------------------------------------------------------------------------------------+
  121. | as | Cast the value to a given type if possible. |
  122. +------------+---------------------------------------------------------------------------------------------------------------+
  123. | self | Refers to current class instance. |
  124. +------------+---------------------------------------------------------------------------------------------------------------+
  125. | tool | Executes the script in the editor. |
  126. +------------+---------------------------------------------------------------------------------------------------------------+
  127. | signal | Defines a signal. |
  128. +------------+---------------------------------------------------------------------------------------------------------------+
  129. | func | Defines a function. |
  130. +------------+---------------------------------------------------------------------------------------------------------------+
  131. | static | Defines a static function. Static member variables are not allowed. |
  132. +------------+---------------------------------------------------------------------------------------------------------------+
  133. | const | Defines a constant. |
  134. +------------+---------------------------------------------------------------------------------------------------------------+
  135. | enum | Defines an enum. |
  136. +------------+---------------------------------------------------------------------------------------------------------------+
  137. | var | Defines a variable. |
  138. +------------+---------------------------------------------------------------------------------------------------------------+
  139. | onready | Initializes a variable once the Node the script is attached to and its children are part of the scene tree. |
  140. +------------+---------------------------------------------------------------------------------------------------------------+
  141. | export | Saves a variable along with the resource it's attached to and makes it visible and modifiable in the editor. |
  142. +------------+---------------------------------------------------------------------------------------------------------------+
  143. | setget | Defines setter and getter functions for a variable. |
  144. +------------+---------------------------------------------------------------------------------------------------------------+
  145. | breakpoint | Editor helper for debugger breakpoints. |
  146. +------------+---------------------------------------------------------------------------------------------------------------+
  147. | preload | Preloads a class or variable. See `Classes as resources`_. |
  148. +------------+---------------------------------------------------------------------------------------------------------------+
  149. | yield | Coroutine support. See `Coroutines with yield`_. |
  150. +------------+---------------------------------------------------------------------------------------------------------------+
  151. | assert | Asserts a condition, logs error on failure. Ignored in non-debug builds. See `Assert keyword`_. |
  152. +------------+---------------------------------------------------------------------------------------------------------------+
  153. | remote | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  154. +------------+---------------------------------------------------------------------------------------------------------------+
  155. | master | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  156. +------------+---------------------------------------------------------------------------------------------------------------+
  157. | puppet | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  158. +------------+---------------------------------------------------------------------------------------------------------------+
  159. | remotesync | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  160. +------------+---------------------------------------------------------------------------------------------------------------+
  161. | mastersync | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  162. +------------+---------------------------------------------------------------------------------------------------------------+
  163. | puppetsync | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  164. +------------+---------------------------------------------------------------------------------------------------------------+
  165. | PI | PI constant. |
  166. +------------+---------------------------------------------------------------------------------------------------------------+
  167. | TAU | TAU constant. |
  168. +------------+---------------------------------------------------------------------------------------------------------------+
  169. | INF | Infinity constant. Used for comparisons. |
  170. +------------+---------------------------------------------------------------------------------------------------------------+
  171. | NAN | NAN (not a number) constant. Used for comparisons. |
  172. +------------+---------------------------------------------------------------------------------------------------------------+
  173. Operators
  174. ~~~~~~~~~
  175. The following is the list of supported operators and their precedence.
  176. +---------------------------------------------------------------+-----------------------------------------+
  177. | **Operator** | **Description** |
  178. +---------------------------------------------------------------+-----------------------------------------+
  179. | ``x[index]`` | Subscription (highest priority) |
  180. +---------------------------------------------------------------+-----------------------------------------+
  181. | ``x.attribute`` | Attribute reference |
  182. +---------------------------------------------------------------+-----------------------------------------+
  183. | ``foo()`` | Function call |
  184. +---------------------------------------------------------------+-----------------------------------------+
  185. | ``is`` | Instance type checker |
  186. +---------------------------------------------------------------+-----------------------------------------+
  187. | ``~`` | Bitwise NOT |
  188. +---------------------------------------------------------------+-----------------------------------------+
  189. | ``-x`` | Negative / Unary negation |
  190. +---------------------------------------------------------------+-----------------------------------------+
  191. | ``*`` ``/`` ``%`` | Multiplication / Division / Remainder |
  192. | | |
  193. | | These operators have the same behavior |
  194. | | as C++. Integer division is truncated |
  195. | | rather than returning a fractional |
  196. | | number, and the % operator is only |
  197. | | available for ints ("fmod" for floats) |
  198. +---------------------------------------------------------------+-----------------------------------------+
  199. | ``+`` | Addition / Concatenation of arrays |
  200. +---------------------------------------------------------------+-----------------------------------------+
  201. | ``-`` | Subtraction |
  202. +---------------------------------------------------------------+-----------------------------------------+
  203. | ``<<`` ``>>`` | Bit shifting |
  204. +---------------------------------------------------------------+-----------------------------------------+
  205. | ``&`` | Bitwise AND |
  206. +---------------------------------------------------------------+-----------------------------------------+
  207. | ``^`` | Bitwise XOR |
  208. +---------------------------------------------------------------+-----------------------------------------+
  209. | ``|`` | Bitwise OR |
  210. +---------------------------------------------------------------+-----------------------------------------+
  211. | ``<`` ``>`` ``==`` ``!=`` ``>=`` ``<=`` | Comparisons |
  212. +---------------------------------------------------------------+-----------------------------------------+
  213. | ``in`` | Content test |
  214. +---------------------------------------------------------------+-----------------------------------------+
  215. | ``!`` ``not`` | Boolean NOT |
  216. +---------------------------------------------------------------+-----------------------------------------+
  217. | ``and`` ``&&`` | Boolean AND |
  218. +---------------------------------------------------------------+-----------------------------------------+
  219. | ``or`` ``||`` | Boolean OR |
  220. +---------------------------------------------------------------+-----------------------------------------+
  221. | ``if x else`` | Ternary if/else |
  222. +---------------------------------------------------------------+-----------------------------------------+
  223. | ``as`` | Type casting |
  224. +---------------------------------------------------------------+-----------------------------------------+
  225. | ``=`` ``+=`` ``-=`` ``*=`` ``/=`` ``%=`` ``&=`` ``|=`` | Assignment (lowest priority) |
  226. +---------------------------------------------------------------+-----------------------------------------+
  227. Literals
  228. ~~~~~~~~
  229. +--------------------------+----------------------------------------+
  230. | **Literal** | **Type** |
  231. +--------------------------+----------------------------------------+
  232. | ``45`` | Base 10 integer |
  233. +--------------------------+----------------------------------------+
  234. | ``0x8F51`` | Base 16 (hexadecimal) integer |
  235. +--------------------------+----------------------------------------+
  236. | ``0b101010`` | Base 2 (binary) integer |
  237. +--------------------------+----------------------------------------+
  238. | ``3.14``, ``58.1e-10`` | Floating-point number (real) |
  239. +--------------------------+----------------------------------------+
  240. | ``"Hello"``, ``"Hi"`` | Strings |
  241. +--------------------------+----------------------------------------+
  242. | ``"""Hello"""`` | Multiline string |
  243. +--------------------------+----------------------------------------+
  244. | ``@"Node/Label"`` | :ref:`class_NodePath` or StringName |
  245. +--------------------------+----------------------------------------+
  246. | ``$NodePath`` | Shorthand for ``get_node("NodePath")`` |
  247. +--------------------------+----------------------------------------+
  248. Comments
  249. ~~~~~~~~
  250. Anything from a ``#`` to the end of the line is ignored and is
  251. considered a comment.
  252. ::
  253. # This is a comment.
  254. .. _doc_gdscript_builtin_types:
  255. Built-in types
  256. --------------
  257. Built-in types are stack-allocated. They are passed as values. This means a copy
  258. is created on each assignment or when passing them as arguments to functions.
  259. The only exceptions are ``Array``\ s and ``Dictionaries``, which are passed by
  260. reference so they are shared. (Pooled arrays such as ``PoolByteArray`` are still
  261. passed as values.)
  262. Basic built-in types
  263. ~~~~~~~~~~~~~~~~~~~~
  264. A variable in GDScript can be assigned to several built-in types.
  265. null
  266. ^^^^
  267. ``null`` is an empty data type that contains no information and can not
  268. be assigned any other value.
  269. :ref:`bool <class_bool>`
  270. ^^^^^^^^^^^^^^^^^^^^^^^^
  271. Short for "boolean", it can only contain ``true`` or ``false``.
  272. :ref:`int <class_int>`
  273. ^^^^^^^^^^^^^^^^^^^^^^
  274. Short for "integer", it stores whole numbers (positive and negative).
  275. It is stored as a 64-bit value, equivalent to "int64_t" in C++.
  276. :ref:`float <class_float>`
  277. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  278. Stores real numbers, including decimals, using floating-point values.
  279. It is stored as a 64-bit value, equivalent to "double" in C++.
  280. Note: Currently, data structures such as Vector2, Vector3, and
  281. PoolRealArray store 32-bit single-precision "float" values.
  282. :ref:`String <class_String>`
  283. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  284. A sequence of characters in `Unicode format <https://en.wikipedia.org/wiki/Unicode>`_.
  285. Strings can contain the following escape sequences:
  286. +---------------------+---------------------------------+
  287. | **Escape sequence** | **Expands to** |
  288. +---------------------+---------------------------------+
  289. | ``\n`` | Newline (line feed) |
  290. +---------------------+---------------------------------+
  291. | ``\t`` | Horizontal tab character |
  292. +---------------------+---------------------------------+
  293. | ``\r`` | Carriage return |
  294. +---------------------+---------------------------------+
  295. | ``\a`` | Alert (beep/bell) |
  296. +---------------------+---------------------------------+
  297. | ``\b`` | Backspace |
  298. +---------------------+---------------------------------+
  299. | ``\f`` | Formfeed page break |
  300. +---------------------+---------------------------------+
  301. | ``\v`` | Vertical tab character |
  302. +---------------------+---------------------------------+
  303. | ``\"`` | Double quote |
  304. +---------------------+---------------------------------+
  305. | ``\'`` | Single quote |
  306. +---------------------+---------------------------------+
  307. | ``\\`` | Backslash |
  308. +---------------------+---------------------------------+
  309. | ``\uXXXX`` | Unicode codepoint ``XXXX`` |
  310. | | (hexadecimal, case-insensitive) |
  311. +---------------------+---------------------------------+
  312. GDScript also supports :ref:`doc_gdscript_printf`.
  313. Vector built-in types
  314. ~~~~~~~~~~~~~~~~~~~~~
  315. :ref:`Vector2 <class_Vector2>`
  316. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  317. 2D vector type containing ``x`` and ``y`` fields. Can also be
  318. accessed as an array.
  319. :ref:`Rect2 <class_Rect2>`
  320. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  321. 2D Rectangle type containing two vectors fields: ``position`` and ``size``.
  322. Also contains an ``end`` field which is ``position + size``.
  323. :ref:`Vector3 <class_Vector3>`
  324. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  325. 3D vector type containing ``x``, ``y`` and ``z`` fields. This can also
  326. be accessed as an array.
  327. :ref:`Transform2D <class_Transform2D>`
  328. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  329. 3×2 matrix used for 2D transforms.
  330. :ref:`Plane <class_Plane>`
  331. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  332. 3D Plane type in normalized form that contains a ``normal`` vector field
  333. and a ``d`` scalar distance.
  334. :ref:`Quat <class_Quat>`
  335. ^^^^^^^^^^^^^^^^^^^^^^^^
  336. Quaternion is a datatype used for representing a 3D rotation. It's
  337. useful for interpolating rotations.
  338. :ref:`AABB <class_AABB>`
  339. ^^^^^^^^^^^^^^^^^^^^^^^^
  340. Axis-aligned bounding box (or 3D box) contains 2 vectors fields: ``position``
  341. and ``size``. Also contains an ``end`` field which is
  342. ``position + size``.
  343. :ref:`Basis <class_Basis>`
  344. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  345. 3x3 matrix used for 3D rotation and scale. It contains 3 vector fields
  346. (``x``, ``y`` and ``z``) and can also be accessed as an array of 3D
  347. vectors.
  348. :ref:`Transform <class_Transform>`
  349. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  350. 3D Transform contains a Basis field ``basis`` and a Vector3 field
  351. ``origin``.
  352. Engine built-in types
  353. ~~~~~~~~~~~~~~~~~~~~~
  354. :ref:`Color <class_Color>`
  355. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  356. Color data type contains ``r``, ``g``, ``b``, and ``a`` fields. It can
  357. also be accessed as ``h``, ``s``, and ``v`` for hue/saturation/value.
  358. :ref:`NodePath <class_NodePath>`
  359. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  360. Compiled path to a node used mainly in the scene system. It can be
  361. easily assigned to, and from, a String.
  362. :ref:`RID <class_RID>`
  363. ^^^^^^^^^^^^^^^^^^^^^^
  364. Resource ID (RID). Servers use generic RIDs to reference opaque data.
  365. :ref:`Object <class_Object>`
  366. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  367. Base class for anything that is not a built-in type.
  368. Container built-in types
  369. ~~~~~~~~~~~~~~~~~~~~~~~~
  370. :ref:`Array <class_Array>`
  371. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  372. Generic sequence of arbitrary object types, including other arrays or dictionaries (see below).
  373. The array can resize dynamically. Arrays are indexed starting from index ``0``.
  374. Negative indices count from the end.
  375. ::
  376. var arr = []
  377. arr = [1, 2, 3]
  378. var b = arr[1] # This is 2.
  379. var c = arr[arr.size() - 1] # This is 3.
  380. var d = arr[-1] # Same as the previous line, but shorter.
  381. arr[0] = "Hi!" # Replacing value 1 with "Hi!".
  382. arr.append(4) # Array is now ["Hi!", 2, 3, 4].
  383. GDScript arrays are allocated linearly in memory for speed.
  384. Large arrays (more than tens of thousands of elements) may however cause
  385. memory fragmentation. If this is a concern, special types of
  386. arrays are available. These only accept a single data type. They avoid memory
  387. fragmentation and use less memory, but are atomic and tend to run slower than generic
  388. arrays. They are therefore only recommended to use for large data sets:
  389. - :ref:`PoolByteArray <class_PoolByteArray>`: An array of bytes (integers from 0 to 255).
  390. - :ref:`PoolIntArray <class_PoolIntArray>`: An array of integers.
  391. - :ref:`PoolRealArray <class_PoolRealArray>`: An array of floats.
  392. - :ref:`PoolStringArray <class_PoolStringArray>`: An array of strings.
  393. - :ref:`PoolVector2Array <class_PoolVector2Array>`: An array of :ref:`Vector2 <class_Vector2>` objects.
  394. - :ref:`PoolVector3Array <class_PoolVector3Array>`: An array of :ref:`Vector3 <class_Vector3>` objects.
  395. - :ref:`PoolColorArray <class_PoolColorArray>`: An array of :ref:`Color <class_Color>` objects.
  396. :ref:`Dictionary <class_Dictionary>`
  397. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  398. Associative container which contains values referenced by unique keys.
  399. ::
  400. var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
  401. d["Hi!"] = 0
  402. d = {
  403. 22: "value",
  404. "some_key": 2,
  405. "other_key": [2, 3, 4],
  406. "more_key": "Hello"
  407. }
  408. Lua-style table syntax is also supported. Lua-style uses ``=`` instead of ``:``
  409. and doesn't use quotes to mark string keys (making for slightly less to write).
  410. However, keys written in this form can't start with a digit (like any GDScript
  411. identifier).
  412. ::
  413. var d = {
  414. test22 = "value",
  415. some_key = 2,
  416. other_key = [2, 3, 4],
  417. more_key = "Hello"
  418. }
  419. To add a key to an existing dictionary, access it like an existing key and
  420. assign to it::
  421. var d = {} # Create an empty Dictionary.
  422. d.waiting = 14 # Add String "waiting" as a key and assign the value 14 to it.
  423. d[4] = "hello" # Add integer 4 as a key and assign the String "hello" as its value.
  424. d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it.
  425. var test = 4
  426. # Prints "hello" by indexing the dictionary with a dynamic key.
  427. # This is not the same as `d.test`. The bracket syntax equivalent to
  428. # `d.test` is `d["test"]`.
  429. print(d[test])
  430. .. note::
  431. The bracket syntax can be used to access properties of any
  432. :ref:`class_Object`, not just Dictionaries. Keep in mind it will cause a
  433. script error when attempting to index a non-existing property. To avoid
  434. this, use the :ref:`Object.get() <class_Object_method_get>` and
  435. :ref:`Object.set() <class_Object_method_set>` methods instead.
  436. Data
  437. ----
  438. Variables
  439. ~~~~~~~~~
  440. Variables can exist as class members or local to functions. They are
  441. created with the ``var`` keyword and may, optionally, be assigned a
  442. value upon initialization.
  443. ::
  444. var a # Data type is 'null' by default.
  445. var b = 5
  446. var c = 3.8
  447. var d = b + c # Variables are always initialized in order.
  448. Variables can optionally have a type specification. When a type is specified,
  449. the variable will be forced to have always that same type, and trying to assign
  450. an incompatible value will raise an error.
  451. Types are specified in the variable declaration using a ``:`` (colon) symbol
  452. after the variable name, followed by the type.
  453. ::
  454. var my_vector2: Vector2
  455. var my_node: Node = Sprite.new()
  456. If the variable is initialized within the declaration, the type can be inferred, so
  457. it's possible to omit the type name::
  458. var my_vector2 := Vector2() # 'my_vector2' is of type 'Vector2'.
  459. var my_node := Sprite.new() # 'my_node' is of type 'Sprite'.
  460. Type inference is only possible if the assigned value has a defined type, otherwise
  461. it will raise an error.
  462. Valid types are:
  463. - Built-in types (Array, Vector2, int, String, etc.).
  464. - Engine classes (Node, Resource, Reference, etc.).
  465. - Constant names if they contain a script resource (``MyScript`` if you declared ``const MyScript = preload("res://my_script.gd")``).
  466. - Other classes in the same script, respecting scope (``InnerClass.NestedClass`` if you declared ``class NestedClass`` inside the ``class InnerClass`` in the same scope).
  467. - Script classes declared with the ``class_name`` keyword.
  468. Casting
  469. ^^^^^^^
  470. Values assigned to typed variables must have a compatible type. If it's needed to
  471. coerce a value to be of a certain type, in particular for object types, you can
  472. use the casting operator ``as``.
  473. Casting between object types results in the same object if the value is of the
  474. same type or a subtype of the cast type.
  475. ::
  476. var my_node2D: Node2D
  477. my_node2D = $Sprite as Node2D # Works since Sprite is a subtype of Node2D.
  478. If the value is not a subtype, the casting operation will result in a ``null`` value.
  479. ::
  480. var my_node2D: Node2D
  481. my_node2D = $Button as Node2D # Results in 'null' since a Button is not a subtype of Node2D.
  482. For built-in types, they will be forcibly converted if possible, otherwise the
  483. engine will raise an error.
  484. ::
  485. var my_int: int
  486. my_int = "123" as int # The string can be converted to int.
  487. my_int = Vector2() as int # A Vector2 can't be converted to int, this will cause an error.
  488. Casting is also useful to have better type-safe variables when interacting with
  489. the scene tree::
  490. # Will infer the variable to be of type Sprite.
  491. var my_sprite := $Character as Sprite
  492. # Will fail if $AnimPlayer is not an AnimationPlayer, even if it has the method 'play()'.
  493. ($AnimPlayer as AnimationPlayer).play("walk")
  494. Constants
  495. ~~~~~~~~~
  496. Constants are similar to variables, but must be constants or constant
  497. expressions and must be assigned on initialization.
  498. ::
  499. const A = 5
  500. const B = Vector2(20, 20)
  501. const C = 10 + 20 # Constant expression.
  502. const D = Vector2(20, 30).x # Constant expression: 20.
  503. const E = [1, 2, 3, 4][0] # Constant expression: 1.
  504. const F = sin(20) # 'sin()' can be used in constant expressions.
  505. const G = x + 20 # Invalid; this is not a constant expression!
  506. const H = A + 20 # Constant expression: 25 (`A` is a constant).
  507. Although the type of constants is inferred from the assigned value, it's also
  508. possible to add explicit type specification::
  509. const A: int = 5
  510. const B: Vector2 = Vector2()
  511. Assigning a value of an incompatible type will raise an error.
  512. .. note::
  513. Since arrays and dictionaries are passed by reference, constants are "flat".
  514. This means that if you declare a constant array or dictionary, it can still
  515. be modified afterwards. They can't be reassigned with another value though.
  516. Enums
  517. ^^^^^
  518. Enums are basically a shorthand for constants, and are pretty useful if you
  519. want to assign consecutive integers to some constant.
  520. If you pass a name to the enum, it will put all the keys inside a constant
  521. dictionary of that name.
  522. .. important:: In Godot 3.1 and later, keys in a named enum are not registered
  523. as global constants. They should be accessed prefixed by the
  524. enum's name (``Name.KEY``); see an example below.
  525. ::
  526. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  527. # Is the same as:
  528. const TILE_BRICK = 0
  529. const TILE_FLOOR = 1
  530. const TILE_SPIKE = 2
  531. const TILE_TELEPORT = 3
  532. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  533. # Is the same as:
  534. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  535. # Access values with State.STATE_IDLE, etc.
  536. Functions
  537. ~~~~~~~~~
  538. Functions always belong to a `class <Classes_>`_. The scope priority for
  539. variable look-up is: local → class member → global. The ``self`` variable is
  540. always available and is provided as an option for accessing class members, but
  541. is not always required (and should *not* be sent as the function's first
  542. argument, unlike Python).
  543. ::
  544. func my_function(a, b):
  545. print(a)
  546. print(b)
  547. return a + b # Return is optional; without it 'null' is returned.
  548. A function can ``return`` at any point. The default return value is ``null``.
  549. Functions can also have type specification for the arguments and for the return
  550. value. Types for arguments can be added in a similar way to variables::
  551. func my_function(a: int, b: String):
  552. pass
  553. If a function argument has a default value, it's possible to infer the type::
  554. func my_function(int_arg := 42, String_arg := "string"):
  555. pass
  556. The return type of the function can be specified after the arguments list using
  557. the arrow token (``->``)::
  558. func my_int_function() -> int:
  559. return 0
  560. Functions that have a return type **must** return a proper value. Setting the
  561. type as ``void`` means the function doesn't return anything. Void functions can
  562. return early with the ``return`` keyword, but they can't return any value.
  563. ::
  564. void_function() -> void:
  565. return # Can't return a value
  566. .. note:: Non-void functions must **always** return a value, so if your code has
  567. branching statements (such as an ``if``/``else`` construct), all the
  568. possible paths must have a return. E.g., if you have a ``return``
  569. inside an ``if`` block but not after it, the editor will raise an
  570. error because if the block is not executed, the function won't have a
  571. valid value to return.
  572. Referencing functions
  573. ^^^^^^^^^^^^^^^^^^^^^
  574. Contrary to Python, functions are *not* first-class objects in GDScript. This
  575. means they cannot be stored in variables, passed as an argument to another
  576. function or be returned from other functions. This is for performance reasons.
  577. To reference a function by name at run-time, (e.g. to store it in a variable, or
  578. pass it to another function as an argument) one must use the ``call`` or
  579. ``funcref`` helpers::
  580. # Call a function by name in one step.
  581. my_node.call("my_function", args)
  582. # Store a function reference.
  583. var my_func = funcref(my_node, "my_function")
  584. # Call stored function reference.
  585. my_func.call_func(args)
  586. Static functions
  587. ^^^^^^^^^^^^^^^^
  588. A function can be declared static. When a function is static, it has no
  589. access to the instance member variables or ``self``. This is mainly
  590. useful to make libraries of helper functions::
  591. static func sum2(a, b):
  592. return a + b
  593. Statements and control flow
  594. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  595. Statements are standard and can be assignments, function calls, control
  596. flow structures, etc (see below). ``;`` as a statement separator is
  597. entirely optional.
  598. if/else/elif
  599. ^^^^^^^^^^^^
  600. Simple conditions are created by using the ``if``/``else``/``elif`` syntax.
  601. Parenthesis around conditions are allowed, but not required. Given the
  602. nature of the tab-based indentation, ``elif`` can be used instead of
  603. ``else``/``if`` to maintain a level of indentation.
  604. ::
  605. if [expression]:
  606. statement(s)
  607. elif [expression]:
  608. statement(s)
  609. else:
  610. statement(s)
  611. Short statements can be written on the same line as the condition::
  612. if 1 + 1 == 2: return 2 + 2
  613. else:
  614. var x = 3 + 3
  615. return x
  616. Sometimes, you might want to assign a different initial value based on a
  617. boolean expression. In this case, ternary-if expressions come in handy::
  618. var x = [value] if [expression] else [value]
  619. y += 3 if y < 10 else -1
  620. while
  621. ^^^^^
  622. Simple loops are created by using ``while`` syntax. Loops can be broken
  623. using ``break`` or continued using ``continue``:
  624. ::
  625. while [expression]:
  626. statement(s)
  627. for
  628. ^^^
  629. To iterate through a range, such as an array or table, a *for* loop is
  630. used. When iterating over an array, the current array element is stored in
  631. the loop variable. When iterating over a dictionary, the *key* is stored
  632. in the loop variable.
  633. ::
  634. for x in [5, 7, 11]:
  635. statement # Loop iterates 3 times with 'x' as 5, then 7 and finally 11.
  636. var dict = {"a": 0, "b": 1, "c": 2}
  637. for i in dict:
  638. print(dict[i]) # Prints 0, then 1, then 2.
  639. for i in range(3):
  640. statement # Similar to [0, 1, 2] but does not allocate an array.
  641. for i in range(1, 3):
  642. statement # Similar to [1, 2] but does not allocate an array.
  643. for i in range(2, 8, 2):
  644. statement # Similar to [2, 4, 6] but does not allocate an array.
  645. for c in "Hello":
  646. print(c) # Iterate through all characters in a String, print every letter on new line.
  647. for i in 3:
  648. statement # Similar to range(3)
  649. for i in 2.2:
  650. statement # Similar to range(ceil(2.2))
  651. match
  652. ^^^^^
  653. A ``match`` statement is used to branch execution of a program.
  654. It's the equivalent of the ``switch`` statement found in many other languages, but offers some additional features.
  655. Basic syntax::
  656. match [expression]:
  657. [pattern](s):
  658. [block]
  659. [pattern](s):
  660. [block]
  661. [pattern](s):
  662. [block]
  663. **Crash-course for people who are familiar with switch statements**:
  664. 1. Replace ``switch`` with ``match``.
  665. 2. Remove ``case``.
  666. 3. Remove any ``break``\ s. If you don't want to ``break`` by default, you can use ``continue`` for a fallthrough.
  667. 4. Change ``default`` to a single underscore.
  668. **Control flow**:
  669. The patterns are matched from top to bottom.
  670. If a pattern matches, the first corresponding block will be executed. After that, the execution continues below the ``match`` statement.
  671. You can use ``continue`` to stop execution in the current block and check for an additional match in the patterns below it.
  672. There are 6 pattern types:
  673. - Constant pattern
  674. Constant primitives, like numbers and strings::
  675. match x:
  676. 1:
  677. print("We are number one!")
  678. 2:
  679. print("Two are better than one!")
  680. "test":
  681. print("Oh snap! It's a string!")
  682. - Variable pattern
  683. Matches the contents of a variable/enum::
  684. match typeof(x):
  685. TYPE_REAL:
  686. print("float")
  687. TYPE_STRING:
  688. print("text")
  689. TYPE_ARRAY:
  690. print("array")
  691. - Wildcard pattern
  692. This pattern matches everything. It's written as a single underscore.
  693. It can be used as the equivalent of the ``default`` in a ``switch`` statement in other languages::
  694. match x:
  695. 1:
  696. print("It's one!")
  697. 2:
  698. print("It's one times two!")
  699. _:
  700. print("It's not 1 or 2. I don't care to be honest.")
  701. - Binding pattern
  702. A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name.
  703. It's especially useful in array and dictionary patterns::
  704. match x:
  705. 1:
  706. print("It's one!")
  707. 2:
  708. print("It's one times two!")
  709. var new_var:
  710. print("It's not 1 or 2, it's ", new_var)
  711. - Array pattern
  712. Matches an array. Every single element of the array pattern is a pattern itself, so you can nest them.
  713. The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  714. **Open-ended array**: An array can be bigger than the pattern by making the last subpattern ``..``.
  715. Every subpattern has to be comma-separated.
  716. ::
  717. match x:
  718. []:
  719. print("Empty array")
  720. [1, 3, "test", null]:
  721. print("Very specific array")
  722. [var start, _, "test"]:
  723. print("First element is ", start, ", and the last is \"test\"")
  724. [42, ..]:
  725. print("Open ended array")
  726. - Dictionary pattern
  727. Works in the same way as the array pattern. Every key has to be a constant pattern.
  728. The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  729. **Open-ended dictionary**: A dictionary can be bigger than the pattern by making the last subpattern ``..``.
  730. Every subpattern has to be comma separated.
  731. If you don't specify a value, then only the existence of the key is checked.
  732. A value pattern is separated from the key pattern with a ``:``.
  733. ::
  734. match x:
  735. {}:
  736. print("Empty dict")
  737. {"name": "Dennis"}:
  738. print("The name is Dennis")
  739. {"name": "Dennis", "age": var age}:
  740. print("Dennis is ", age, " years old.")
  741. {"name", "age"}:
  742. print("Has a name and an age, but it's not Dennis :(")
  743. {"key": "godotisawesome", ..}:
  744. print("I only checked for one entry and ignored the rest")
  745. - Multiple patterns
  746. You can also specify multiple patterns separated by a comma. These patterns aren't allowed to have any bindings in them.
  747. ::
  748. match x:
  749. 1, 2, 3:
  750. print("It's 1 - 3")
  751. "Sword", "Splash potion", "Fist":
  752. print("Yep, you've taken damage")
  753. Classes
  754. ~~~~~~~
  755. By default, all script files are unnamed classes. In this case, you can only
  756. reference them using the file's path, using either a relative or an absolute
  757. path. For example, if you name a script file ``character.gd``::
  758. # Inherit from 'Character.gd'.
  759. extends "res://path/to/character.gd"
  760. # Load character.gd and create a new node instance from it.
  761. var Character = load("res://path/to/character.gd")
  762. var character_node = Character.new()
  763. Instead, you can give your class a name to register it as a new type in Godot's
  764. editor. For that, you use the ``class_name`` keyword. You can add an
  765. optional comma followed by a path to an image, to use it as an icon. Your class
  766. will then appear with its new icon in the editor::
  767. # Item.gd
  768. extends Node
  769. class_name Item, "res://interface/icons/item.png"
  770. .. image:: img/class_name_editor_register_example.png
  771. Here's a class file example:
  772. ::
  773. # Saved as a file named 'character.gd'.
  774. class_name Character
  775. var health = 5
  776. func print_health():
  777. print(health)
  778. func print_this_script_three_times():
  779. print(get_script())
  780. print(ResourceLoader.load("res://character.gd"))
  781. print(Character)
  782. .. note:: Godot's class syntax is compact: it can only contain member variables or
  783. functions. You can use static functions, but not static member variables. In the
  784. same way, the engine initializes variables every time you create an instance,
  785. and this includes arrays and dictionaries. This is in the spirit of thread
  786. safety, since scripts can be initialized in separate threads without the user
  787. knowing.
  788. Inheritance
  789. ^^^^^^^^^^^
  790. A class (stored as a file) can inherit from:
  791. - A global class.
  792. - Another class file.
  793. - An inner class inside another class file.
  794. Multiple inheritance is not allowed.
  795. Inheritance uses the ``extends`` keyword::
  796. # Inherit/extend a globally available class.
  797. extends SomeClass
  798. # Inherit/extend a named class file.
  799. extends "somefile.gd"
  800. # Inherit/extend an inner class in another file.
  801. extends "somefile.gd".SomeInnerClass
  802. To check if a given instance inherits from a given class,
  803. the ``is`` keyword can be used::
  804. # Cache the enemy class.
  805. const Enemy = preload("enemy.gd")
  806. # [...]
  807. # Use 'is' to check inheritance.
  808. if entity is Enemy:
  809. entity.apply_damage()
  810. To call a function in a *parent class* (i.e. one ``extend``-ed in your current
  811. class), prepend ``.`` to the function name::
  812. .base_func(args)
  813. This is especially useful because functions in extending classes replace
  814. functions with the same name in their parent classes. If you still want to
  815. call them, you can prefix them with ``.`` (like the ``super`` keyword
  816. in other languages)::
  817. func some_func(x):
  818. .some_func(x) # Calls the same function on the parent class.
  819. .. note:: Default functions like ``_init``, and most notifications such as
  820. ``_enter_tree``, ``_exit_tree``, ``_process``, ``_physics_process``,
  821. etc. are called in all parent classes automatically.
  822. There is no need to call them explicitly when overloading them.
  823. Class Constructor
  824. ^^^^^^^^^^^^^^^^^
  825. The class constructor, called on class instantiation, is named ``_init``. As
  826. mentioned earlier, the constructors of parent classes are called automatically
  827. when inheriting a class. So, there is usually no need to call ``._init()``
  828. explicitly.
  829. Unlike the call of a regular function, like in the above example with
  830. ``.some_func``, if the constructor from the inherited class takes arguments,
  831. they are passed like this::
  832. func _init(args).(parent_args):
  833. pass
  834. This is better explained through examples. Consider this scenario::
  835. # State.gd (inherited class)
  836. var entity = null
  837. var message = null
  838. func _init(e=null):
  839. entity = e
  840. func enter(m):
  841. message = m
  842. # Idle.gd (inheriting class)
  843. extends "State.gd"
  844. func _init(e=null, m=null).(e):
  845. # Do something with 'e'.
  846. message = m
  847. There are a few things to keep in mind here:
  848. 1. If the inherited class (``State.gd``) defines a ``_init`` constructor that takes
  849. arguments (``e`` in this case), then the inheriting class (``Idle.gd``) *must*
  850. define ``_init`` as well and pass appropriate parameters to ``_init`` from ``State.gd``.
  851. 2. ``Idle.gd`` can have a different number of arguments than the parent class ``State.gd``.
  852. 3. In the example above, ``e`` passed to the ``State.gd`` constructor is the same ``e`` passed
  853. in to ``Idle.gd``.
  854. 4. If ``Idle.gd``'s ``_init`` constructor takes 0 arguments, it still needs to pass some value
  855. to the ``State.gd`` parent class, even if it does nothing. This brings us to the fact that you
  856. can pass literals in the base constructor as well, not just variables. eg.::
  857. # Idle.gd
  858. func _init().(5):
  859. pass
  860. Inner classes
  861. ^^^^^^^^^^^^^
  862. A class file can contain inner classes. Inner classes are defined using the
  863. ``class`` keyword. They are instanced using the ``ClassName.new()``
  864. function.
  865. ::
  866. # Inside a class file.
  867. # An inner class in this class file.
  868. class SomeInnerClass:
  869. var a = 5
  870. func print_value_of_a():
  871. print(a)
  872. # This is the constructor of the class file's main class.
  873. func _init():
  874. var c = SomeInnerClass.new()
  875. c.print_value_of_a()
  876. .. _doc_gdscript_classes_as_resources:
  877. Classes as resources
  878. ^^^^^^^^^^^^^^^^^^^^
  879. Classes stored as files are treated as :ref:`resources <class_GDScript>`. They
  880. must be loaded from disk to access them in other classes. This is done using
  881. either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
  882. class resource is done by calling the ``new`` function on the class object::
  883. # Load the class resource when calling load().
  884. var my_class = load("myclass.gd")
  885. # Preload the class only once at compile time.
  886. const MyClass = preload("myclass.gd")
  887. func _init():
  888. var a = MyClass.new()
  889. a.some_function()
  890. Exports
  891. ~~~~~~~
  892. .. note::
  893. Documentation about exports has been moved to :ref:`doc_gdscript_exports`.
  894. Setters/getters
  895. ~~~~~~~~~~~~~~~
  896. It is often useful to know when a class' member variable changes for
  897. whatever reason. It may also be desired to encapsulate its access in some way.
  898. For this, GDScript provides a *setter/getter* syntax using the ``setget`` keyword.
  899. It is used directly after a variable definition:
  900. ::
  901. var variable = value setget setterfunc, getterfunc
  902. Whenever the value of ``variable`` is modified by an *external* source
  903. (i.e. not from local usage in the class), the *setter* function (``setterfunc`` above)
  904. will be called. This happens *before* the value is changed. The *setter* must decide what to do
  905. with the new value. Vice versa, when ``variable`` is accessed, the *getter* function
  906. (``getterfunc`` above) must ``return`` the desired value. Below is an example::
  907. var my_var setget my_var_set, my_var_get
  908. func my_var_set(new_value):
  909. my_var = new_value
  910. func my_var_get():
  911. return my_var # Getter must return a value.
  912. Either of the *setter* or *getter* functions can be omitted::
  913. # Only a setter.
  914. var my_var = 5 setget my_var_set
  915. # Only a getter (note the comma).
  916. var my_var = 5 setget ,my_var_get
  917. Setters and getters are useful when :ref:`exporting variables <doc_gdscript_exports>`
  918. to the editor in tool scripts or plugins, for validating input.
  919. As said, *local* access will *not* trigger the setter and getter. Here is an
  920. illustration of this:
  921. ::
  922. func _init():
  923. # Does not trigger setter/getter.
  924. my_integer = 5
  925. print(my_integer)
  926. # Does trigger setter/getter.
  927. self.my_integer = 5
  928. print(self.my_integer)
  929. .. _doc_gdscript_tool_mode:
  930. Tool mode
  931. ~~~~~~~~~
  932. By default, scripts don't run inside the editor and only the exported
  933. properties can be changed. In some cases, it is desired that they do run
  934. inside the editor (as long as they don't execute game code or manually
  935. avoid doing so). For this, the ``tool`` keyword exists and must be
  936. placed at the top of the file::
  937. tool
  938. extends Button
  939. func _ready():
  940. print("Hello")
  941. See :ref:`doc_running_code_in_the_editor` for more information.
  942. .. warning:: Be cautious when freeing nodes with ``queue_free()`` or ``free()``
  943. in a tool script (especially the script's owner itself). As tool
  944. scripts run their code in the editor, misusing them may lead to
  945. crashing the editor.
  946. Memory management
  947. ~~~~~~~~~~~~~~~~~
  948. If a class inherits from :ref:`class_Reference`, then instances will be
  949. freed when no longer in use. No garbage collector exists, just
  950. reference counting. By default, all classes that don't define
  951. inheritance extend **Reference**. If this is not desired, then a class
  952. must inherit :ref:`class_Object` manually and must call ``instance.free()``. To
  953. avoid reference cycles that can't be freed, a ``weakref`` function is
  954. provided for creating weak references.
  955. Alternatively, when not using references, the
  956. ``is_instance_valid(instance)`` can be used to check if an object has been
  957. freed.
  958. .. _doc_gdscript_signals:
  959. Signals
  960. ~~~~~~~
  961. Signals are a tool to emit messages from an object that other objects can react
  962. to. To create custom signals for a class, use the ``signal`` keyword.
  963. ::
  964. extends Node
  965. # A signal named health_depleted.
  966. signal health_depleted
  967. .. note::
  968. Signals are a `Callback
  969. <https://en.wikipedia.org/wiki/Callback_(computer_programming)>`_
  970. mechanism. They also fill the role of Observers, a common programming
  971. pattern. For more information, read the `Observer tutorial
  972. <https://gameprogrammingpatterns.com/observer.html>`_ in the
  973. Game Programming Patterns ebook.
  974. You can connect these signals to methods the same way you connect built-in
  975. signals of nodes like :ref:`class_Button` or :ref:`class_RigidBody`.
  976. In the example below, we connect the ``health_depleted`` signal from a
  977. ``Character`` node to a ``Game`` node. When the ``Character`` node emits the
  978. signal, the game node's ``_on_Character_health_depleted`` is called::
  979. # Game.gd
  980. func _ready():
  981. var character_node = get_node('Character')
  982. character_node.connect("health_depleted", self, "_on_Character_health_depleted")
  983. func _on_Character_health_depleted():
  984. get_tree().reload_current_scene()
  985. You can emit as many arguments as you want along with a signal.
  986. Here is an example where this is useful. Let's say we want a life bar on screen
  987. to react to health changes with an animation, but we want to keep the user
  988. interface separate from the player in our scene tree.
  989. In our ``Character.gd`` script, we define a ``health_changed`` signal and emit
  990. it with :ref:`Object.emit_signal() <class_Object_method_emit_signal>`, and from
  991. a ``Game`` node higher up our scene tree, we connect it to the ``Lifebar`` using
  992. the :ref:`Object.connect() <class_Object_method_connect>` method::
  993. # Character.gd
  994. ...
  995. signal health_changed
  996. func take_damage(amount):
  997. var old_health = health
  998. health -= amount
  999. # We emit the health_changed signal every time the
  1000. # character takes damage.
  1001. emit_signal("health_changed", old_health, health)
  1002. ...
  1003. ::
  1004. # Lifebar.gd
  1005. # Here, we define a function to use as a callback when the
  1006. # character's health_changed signal is emitted.
  1007. ...
  1008. func _on_Character_health_changed(old_value, new_value):
  1009. if old_value > new_value:
  1010. progress_bar.modulate = Color.red
  1011. else:
  1012. progress_bar.modulate = Color.green
  1013. # Imagine that `animate` is a user-defined function that animates the
  1014. # bar filling up or emptying itself.
  1015. progress_bar.animate(old_value, new_value)
  1016. ...
  1017. .. note::
  1018. To use signals, your class has to extend the ``Object`` class or any
  1019. type extending it like ``Node``, ``KinematicBody``, ``Control``...
  1020. In the ``Game`` node, we get both the ``Character`` and ``Lifebar`` nodes, then
  1021. connect the character, that emits the signal, to the receiver, the ``Lifebar``
  1022. node in this case.
  1023. ::
  1024. # Game.gd
  1025. func _ready():
  1026. var character_node = get_node('Character')
  1027. var lifebar_node = get_node('UserInterface/Lifebar')
  1028. character_node.connect("health_changed", lifebar_node, "_on_Character_health_changed")
  1029. This allows the ``Lifebar`` to react to health changes without coupling it to
  1030. the ``Character`` node.
  1031. You can write optional argument names in parentheses after the signal's
  1032. definition::
  1033. # Defining a signal that forwards two arguments.
  1034. signal health_changed(old_value, new_value)
  1035. These arguments show up in the editor's node dock, and Godot can use them to
  1036. generate callback functions for you. However, you can still emit any number of
  1037. arguments when you emit signals; it's up to you to emit the correct values.
  1038. .. image:: img/gdscript_basics_signals_node_tab_1.png
  1039. GDScript can bind an array of values to connections between a signal
  1040. and a method. When the signal is emitted, the callback method receives
  1041. the bound values. These bound arguments are unique to each connection,
  1042. and the values will stay the same.
  1043. You can use this array of values to add extra constant information to the
  1044. connection if the emitted signal itself doesn't give you access to all the data
  1045. that you need.
  1046. Building on the example above, let's say we want to display a log of the damage
  1047. taken by each character on the screen, like ``Player1 took 22 damage.``. The
  1048. ``health_changed`` signal doesn't give us the name of the character that took
  1049. damage. So when we connect the signal to the in-game console, we can add the
  1050. character's name in the binds array argument::
  1051. # Game.gd
  1052. func _ready():
  1053. var character_node = get_node('Character')
  1054. var battle_log_node = get_node('UserInterface/BattleLog')
  1055. character_node.connect("health_changed", battle_log_node, "_on_Character_health_changed", [character_node.name])
  1056. Our ``BattleLog`` node receives each element in the binds array as an extra argument::
  1057. # BattleLog.gd
  1058. func _on_Character_health_changed(old_value, new_value, character_name):
  1059. if not new_value <= old_value:
  1060. return
  1061. var damage = old_value - new_value
  1062. label.text += character_name + " took " + str(damage) + " damage."
  1063. Coroutines with yield
  1064. ~~~~~~~~~~~~~~~~~~~~~
  1065. GDScript offers support for `coroutines <https://en.wikipedia.org/wiki/Coroutine>`_
  1066. via the :ref:`yield<class_@GDScript_method_yield>` built-in function. Calling ``yield()`` will
  1067. immediately return from the current function, with the current frozen
  1068. state of the same function as the return value. Calling ``resume()`` on
  1069. this resulting object will continue execution and return whatever the
  1070. function returns. Once resumed, the state object becomes invalid. Here is
  1071. an example::
  1072. func my_func():
  1073. print("Hello")
  1074. yield()
  1075. print("world")
  1076. func _ready():
  1077. var y = my_func()
  1078. # Function state saved in 'y'.
  1079. print("my dear")
  1080. y.resume()
  1081. # 'y' resumed and is now an invalid state.
  1082. Will print::
  1083. Hello
  1084. my dear
  1085. world
  1086. It is also possible to pass values between ``yield()`` and ``resume()``,
  1087. for example::
  1088. func my_func():
  1089. print("Hello")
  1090. print(yield())
  1091. return "cheers!"
  1092. func _ready():
  1093. var y = my_func()
  1094. # Function state saved in 'y'.
  1095. print(y.resume("world"))
  1096. # 'y' resumed and is now an invalid state.
  1097. Will print::
  1098. Hello
  1099. world
  1100. cheers!
  1101. Remember to save the new function state, when using multiple ``yield``\s::
  1102. func co_func():
  1103. for i in range(1, 5):
  1104. print("Turn %d" % i)
  1105. yield();
  1106. func _ready():
  1107. var co = co_func();
  1108. while co is GDScriptFunctionState && co.is_valid():
  1109. co = co.resume();
  1110. Coroutines & signals
  1111. ^^^^^^^^^^^^^^^^^^^^
  1112. The real strength of using ``yield`` is when combined with signals.
  1113. ``yield`` can accept two arguments, an object and a signal. When the
  1114. signal is received, execution will recommence. Here are some examples::
  1115. # Resume execution the next frame.
  1116. yield(get_tree(), "idle_frame")
  1117. # Resume execution when animation is done playing.
  1118. yield(get_node("AnimationPlayer"), "animation_finished")
  1119. # Wait 5 seconds, then resume execution.
  1120. yield(get_tree().create_timer(5.0), "timeout")
  1121. Coroutines themselves use the ``completed`` signal when they transition
  1122. into an invalid state, for example::
  1123. func my_func():
  1124. yield(button_func(), "completed")
  1125. print("All buttons were pressed, hurray!")
  1126. func button_func():
  1127. yield($Button0, "pressed")
  1128. yield($Button1, "pressed")
  1129. ``my_func`` will only continue execution once both buttons have been pressed.
  1130. You can also get the signal's argument once it's emitted by an object:
  1131. ::
  1132. # Wait for when any node is added to the scene tree.
  1133. var node = yield(get_tree(), "node_added")
  1134. If you're unsure whether a function may yield or not, or whether it may yield
  1135. multiple times, you can yield to the ``completed`` signal conditionally:
  1136. ::
  1137. func generate():
  1138. var result = rand_range(-1.0, 1.0)
  1139. if result < 0.0:
  1140. yield(get_tree(), "idle_frame")
  1141. return result
  1142. func make():
  1143. var result = generate()
  1144. if result is GDScriptFunctionState: # Still working.
  1145. result = yield(result, "completed")
  1146. return result
  1147. This ensures that the function returns whatever it was supposed to return
  1148. regardless of whether coroutines were used internally. Note that using
  1149. ``while`` would be redundant here as the ``completed`` signal is only emitted
  1150. when the function didn't yield anymore.
  1151. Onready keyword
  1152. ~~~~~~~~~~~~~~~
  1153. When using nodes, it's common to desire to keep references to parts
  1154. of the scene in a variable. As scenes are only warranted to be
  1155. configured when entering the active scene tree, the sub-nodes can only
  1156. be obtained when a call to ``Node._ready()`` is made.
  1157. ::
  1158. var my_label
  1159. func _ready():
  1160. my_label = get_node("MyLabel")
  1161. This can get a little cumbersome, especially when nodes and external
  1162. references pile up. For this, GDScript has the ``onready`` keyword, that
  1163. defers initialization of a member variable until ``_ready()`` is called. It
  1164. can replace the above code with a single line::
  1165. onready var my_label = get_node("MyLabel")
  1166. Assert keyword
  1167. ~~~~~~~~~~~~~~
  1168. The ``assert`` keyword can be used to check conditions in debug builds. These
  1169. assertions are ignored in non-debug builds. This means that the expression
  1170. passed as argument won't be evaluated in a project exported in release mode.
  1171. Due to this, assertions must **not** contain expressions that have
  1172. side effects. Otherwise, the behavior of the script would vary
  1173. depending on whether the project is run in a debug build.
  1174. ::
  1175. # Check that 'i' is 0. If 'i' is not 0, an assertion error will occur.
  1176. assert(i == 0)
  1177. When running a project from the editor, the project will be paused if an
  1178. assertion error occurs.