gdscript_basics.rst 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  1. .. _doc_gdscript:
  2. GDScript
  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. In the early days, the engine used the `Lua <http://www.lua.org>`__
  15. scripting language. Lua is fast, but creating bindings to an object
  16. oriented system (by using fallbacks) was complex and slow and took an
  17. enormous amount of code. After some experiments with
  18. `Python <http://www.python.org>`__, it also proved difficult to embed.
  19. The last third party scripting language that was used for shipped games
  20. was `Squirrel <http://squirrel-lang.org>`__, but it was dropped as well.
  21. At that point, it became evident that a custom scripting language could
  22. more optimally make use of Godot's particular architecture:
  23. - Godot embeds scripts in nodes. Most languages are not designed with
  24. this in mind.
  25. - Godot uses several built-in data types for 2D and 3D math. Script
  26. languages do not provide this, and binding them is inefficient.
  27. - Godot uses threads heavily for lifting and initializing data from the
  28. net or disk. Script interpreters for common languages are not
  29. friendly to this.
  30. - Godot already has a memory management model for resources, most
  31. script languages provide their own, which results in duplicate
  32. effort and bugs.
  33. - Binding code is always messy and results in several failure points,
  34. unexpected bugs and generally low maintainability.
  35. The result of these considerations is *GDScript*. The language and
  36. interpreter for GDScript ended up being smaller than the binding code itself
  37. for Lua and Squirrel, while having equal functionality. With time, having a
  38. built-in language has proven to be a huge advantage.
  39. Example of GDScript
  40. ~~~~~~~~~~~~~~~~~~~
  41. Some people can learn better by taking a look at the syntax, so
  42. here's a simple example of how GDScript looks.
  43. ::
  44. # A file is a class!
  45. # Inheritance
  46. extends BaseClass
  47. # Member variables
  48. var a = 5
  49. var s = "Hello"
  50. var arr = [1, 2, 3]
  51. var dict = {"key": "value", 2:3}
  52. # Constants
  53. const ANSWER = 42
  54. const THE_NAME = "Charly"
  55. # Enums
  56. enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
  57. enum Named {THING_1, THING_2, ANOTHER_THING = -1}
  58. # Built-in vector types
  59. var v2 = Vector2(1, 2)
  60. var v3 = Vector3(1, 2, 3)
  61. # function
  62. func some_function(param1, param2):
  63. var local_var = 5
  64. if param1 < local_var:
  65. print(param1)
  66. elif param2 > 5:
  67. print(param2)
  68. else:
  69. print("Fail!")
  70. for i in range(20):
  71. print(i)
  72. while param2 != 0:
  73. param2 -= 1
  74. var local_var2 = param1 + 3
  75. return local_var2
  76. # Functions override functions with the same name on the base/parent class.
  77. # If you still want to call them, use '.' (like 'super' in other languages)
  78. func something(p1, p2):
  79. .something(p1, p2)
  80. # Inner class
  81. class Something:
  82. var a = 10
  83. # Constructor
  84. func _init():
  85. print("Constructed!")
  86. var lv = Something.new()
  87. print(lv.a)
  88. If you have previous experience with statically typed languages such as
  89. C, C++, or C# but never used a dynamically typed one before, it is advised you
  90. read this tutorial: :ref:`doc_gdscript_more_efficiently`.
  91. Language
  92. --------
  93. In the following, an overview is given to GDScript. Details, such as which
  94. methods are available to arrays or other objects, should be looked up in
  95. the linked class descriptions.
  96. Identifiers
  97. ~~~~~~~~~~~
  98. Any string that restricts itself to alphabetic characters (``a`` to
  99. ``z`` and ``A`` to ``Z``), digits (``0`` to ``9``) and ``_`` qualifies
  100. as an identifier. Additionally, identifiers must not begin with a digit.
  101. Identifiers are case-sensitive (``foo`` is different from ``FOO``).
  102. Keywords
  103. ~~~~~~~~
  104. The following is the list of keywords supported by the language. Since
  105. keywords are reserved words (tokens), they can't be used as identifiers.
  106. Operators (like ``in``, ``not``, ``and`` or ``or``) and names of built-in types
  107. as listed in the following sections are also reserved.
  108. Keywords are defined in the `GDScript tokenizer <https://github.com/godotengine/godot/blob/master/modules/gdscript/gdscript_tokenizer.cpp>`_
  109. in case you want to take a look under the hood.
  110. +------------+---------------------------------------------------------------------------------------------------------------+
  111. | Keyword | Description |
  112. +============+===============================================================================================================+
  113. | if | See `if/else/elif`_. |
  114. +------------+---------------------------------------------------------------------------------------------------------------+
  115. | elif | See `if/else/elif`_. |
  116. +------------+---------------------------------------------------------------------------------------------------------------+
  117. | else | See `if/else/elif`_. |
  118. +------------+---------------------------------------------------------------------------------------------------------------+
  119. | for | See for_. |
  120. +------------+---------------------------------------------------------------------------------------------------------------+
  121. | do | Reserved for future implementation of do...while loops. |
  122. +------------+---------------------------------------------------------------------------------------------------------------+
  123. | while | See while_. |
  124. +------------+---------------------------------------------------------------------------------------------------------------+
  125. | match | See match_. |
  126. +------------+---------------------------------------------------------------------------------------------------------------+
  127. | switch | Reserved for future implementation. |
  128. +------------+---------------------------------------------------------------------------------------------------------------+
  129. | case | Reserved for future implementation. |
  130. +------------+---------------------------------------------------------------------------------------------------------------+
  131. | break | Exits the execution of the current ``for`` or ``while`` loop. |
  132. +------------+---------------------------------------------------------------------------------------------------------------+
  133. | continue | Immediately skips to the next iteration of the ``for`` or ``while`` loop. |
  134. +------------+---------------------------------------------------------------------------------------------------------------+
  135. | pass | Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions. |
  136. +------------+---------------------------------------------------------------------------------------------------------------+
  137. | return | Returns a value from a function. |
  138. +------------+---------------------------------------------------------------------------------------------------------------+
  139. | class | Defines a class. |
  140. +------------+---------------------------------------------------------------------------------------------------------------+
  141. | extends | Defines what class to extend with the current class. |
  142. +------------+---------------------------------------------------------------------------------------------------------------+
  143. | is | Tests whether a variable extends a given class. |
  144. +------------+---------------------------------------------------------------------------------------------------------------+
  145. | self | Refers to current class instance. |
  146. +------------+---------------------------------------------------------------------------------------------------------------+
  147. | tool | Executes the script in the editor. |
  148. +------------+---------------------------------------------------------------------------------------------------------------+
  149. | signal | Defines a signal. |
  150. +------------+---------------------------------------------------------------------------------------------------------------+
  151. | func | Defines a function. |
  152. +------------+---------------------------------------------------------------------------------------------------------------+
  153. | static | Defines a static function. Static member variables are not allowed. |
  154. +------------+---------------------------------------------------------------------------------------------------------------+
  155. | const | Defines a constant. |
  156. +------------+---------------------------------------------------------------------------------------------------------------+
  157. | enum | Defines an enum. |
  158. +------------+---------------------------------------------------------------------------------------------------------------+
  159. | var | Defines a variable. |
  160. +------------+---------------------------------------------------------------------------------------------------------------+
  161. | onready | Initializes a variable once the Node the script is attached to and its children are part of the scene tree. |
  162. +------------+---------------------------------------------------------------------------------------------------------------+
  163. | export | Saves a variable along with the resource it's attached to and makes it visible and modifiable in the editor. |
  164. +------------+---------------------------------------------------------------------------------------------------------------+
  165. | setget | Defines setter and getter functions for a variable. |
  166. +------------+---------------------------------------------------------------------------------------------------------------+
  167. | breakpoint | Editor helper for debugger breakpoints. |
  168. +------------+---------------------------------------------------------------------------------------------------------------+
  169. | preload | Preloads a class or variable. See `Classes as resources`_. |
  170. +------------+---------------------------------------------------------------------------------------------------------------+
  171. | yield | Coroutine support. See `Coroutines with yield`_. |
  172. +------------+---------------------------------------------------------------------------------------------------------------+
  173. | assert | Asserts a condition, logs error on failure. Ignored in non-debug builds. See `Assert keyword`_. |
  174. +------------+---------------------------------------------------------------------------------------------------------------+
  175. | remote | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  176. +------------+---------------------------------------------------------------------------------------------------------------+
  177. | master | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  178. +------------+---------------------------------------------------------------------------------------------------------------+
  179. | slave | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  180. +------------+---------------------------------------------------------------------------------------------------------------+
  181. | sync | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  182. +------------+---------------------------------------------------------------------------------------------------------------+
  183. | PI | PI constant. |
  184. +------------+---------------------------------------------------------------------------------------------------------------+
  185. | TAU | TAU constant. |
  186. +------------+---------------------------------------------------------------------------------------------------------------+
  187. | INF | Infinity constant. Used for comparisons. |
  188. +------------+---------------------------------------------------------------------------------------------------------------+
  189. | NAN | NAN (not a number) constant. Used for comparisons. |
  190. +------------+---------------------------------------------------------------------------------------------------------------+
  191. Operators
  192. ~~~~~~~~~
  193. The following is the list of supported operators and their precedence.
  194. +---------------------------------------------------------------+-----------------------------------------+
  195. | **Operator** | **Description** |
  196. +---------------------------------------------------------------+-----------------------------------------+
  197. | ``x[index]`` | Subscription, Highest Priority |
  198. +---------------------------------------------------------------+-----------------------------------------+
  199. | ``x.attribute`` | Attribute Reference |
  200. +---------------------------------------------------------------+-----------------------------------------+
  201. | ``is`` | Instance Type Checker |
  202. +---------------------------------------------------------------+-----------------------------------------+
  203. | ``~`` | Bitwise NOT |
  204. +---------------------------------------------------------------+-----------------------------------------+
  205. | ``-x`` | Negative |
  206. +---------------------------------------------------------------+-----------------------------------------+
  207. | ``*`` ``/`` ``%`` | Multiplication / Division / Remainder |
  208. | | |
  209. | | NOTE: The result of these operations |
  210. | | depends on the operands types. If both |
  211. | | are Integers, then the result will be |
  212. | | an Integer. That means 1/10 returns 0 |
  213. | | instead of 0.1. If at least one of the |
  214. | | operands is a float, then the result is |
  215. | | a float: float(1)/10 or 1.0/10 return |
  216. | | both 0.1. |
  217. +---------------------------------------------------------------+-----------------------------------------+
  218. | ``+`` ``-`` | Addition / Subtraction |
  219. +---------------------------------------------------------------+-----------------------------------------+
  220. | ``<<`` ``>>`` | Bit Shifting |
  221. +---------------------------------------------------------------+-----------------------------------------+
  222. | ``&`` | Bitwise AND |
  223. +---------------------------------------------------------------+-----------------------------------------+
  224. | ``^`` | Bitwise XOR |
  225. +---------------------------------------------------------------+-----------------------------------------+
  226. | ``|`` | Bitwise OR |
  227. +---------------------------------------------------------------+-----------------------------------------+
  228. | ``<`` ``>`` ``==`` ``!=`` ``>=`` ``<=`` | Comparisons |
  229. +---------------------------------------------------------------+-----------------------------------------+
  230. | ``in`` | Content Test |
  231. +---------------------------------------------------------------+-----------------------------------------+
  232. | ``!`` ``not`` | Boolean NOT |
  233. +---------------------------------------------------------------+-----------------------------------------+
  234. | ``and`` ``&&`` | Boolean AND |
  235. +---------------------------------------------------------------+-----------------------------------------+
  236. | ``or`` ``||`` | Boolean OR |
  237. +---------------------------------------------------------------+-----------------------------------------+
  238. | ``if x else`` | Ternary if/else |
  239. +---------------------------------------------------------------+-----------------------------------------+
  240. | ``=`` ``+=`` ``-=`` ``*=`` ``/=`` ``%=`` ``&=`` ``|=`` | Assignment, Lowest Priority |
  241. +---------------------------------------------------------------+-----------------------------------------+
  242. Literals
  243. ~~~~~~~~
  244. +--------------------------+--------------------------------+
  245. | **Literal** | **Type** |
  246. +--------------------------+--------------------------------+
  247. | ``45`` | Base 10 integer |
  248. +--------------------------+--------------------------------+
  249. | ``0x8F51`` | Base 16 (hex) integer |
  250. +--------------------------+--------------------------------+
  251. | ``3.14``, ``58.1e-10`` | Floating point number (real) |
  252. +--------------------------+--------------------------------+
  253. | ``"Hello"``, ``"Hi"`` | Strings |
  254. +--------------------------+--------------------------------+
  255. | ``"""Hello"""`` | Multiline string |
  256. +--------------------------+--------------------------------+
  257. | ``@"Node/Label"`` | NodePath or StringName |
  258. +--------------------------+--------------------------------+
  259. Comments
  260. ~~~~~~~~
  261. Anything from a ``#`` to the end of the line is ignored and is
  262. considered a comment.
  263. ::
  264. # This is a comment
  265. Multi-line comments can be created using """ (three quotes in a row) at
  266. the beginning and end of a block of text. Note that this creates a string,
  267. therefore, it will not be stripped away when the script is compiled.
  268. ::
  269. """ Everything on these
  270. lines is considered
  271. a comment """
  272. Built-in types
  273. --------------
  274. Built-in types are stack-allocated. They are passed as values.
  275. This means a copy is created on each assignment or when passing them as arguments to functions.
  276. The only exceptions are ``Array``s and ``Dictionaries``, which are passed by reference so they are shared.
  277. (Not ``PoolArray``s like ``PoolByteArray`` though, those are passed as values too,
  278. so consider this when deciding which to use!)
  279. Basic built-in types
  280. ~~~~~~~~~~~~~~~~~~~~
  281. A variable in GDScript can be assigned to several built-in types.
  282. null
  283. ^^^^
  284. ``null`` is an empty data type that contains no information and can not
  285. be assigned any other value.
  286. bool
  287. ^^^^
  288. The Boolean data type can only contain ``true`` or ``false``.
  289. int
  290. ^^^
  291. The integer data type can only contain integer numbers, (both negative
  292. and positive).
  293. float
  294. ^^^^^
  295. Used to contain a floating point value (real numbers).
  296. :ref:`String <class_String>`
  297. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  298. A sequence of characters in `Unicode format <https://en.wikipedia.org/wiki/Unicode>`_. Strings can contain the
  299. `standard C escape sequences <https://en.wikipedia.org/wiki/Escape_sequences_in_C>`_.
  300. GDScript supports :ref:`format strings aka printf functionality
  301. <doc_gdscript_printf>`.
  302. Vector built-in types
  303. ~~~~~~~~~~~~~~~~~~~~~
  304. :ref:`Vector2 <class_Vector2>`
  305. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  306. 2D vector type containing ``x`` and ``y`` fields. Can also be
  307. accessed as array.
  308. :ref:`Rect2 <class_Rect2>`
  309. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  310. 2D Rectangle type containing two vectors fields: ``position`` and ``size``.
  311. Alternatively contains an ``end`` field which is ``position+size``.
  312. :ref:`Vector3 <class_Vector3>`
  313. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  314. 3D vector type containing ``x``, ``y`` and ``z`` fields. This can also
  315. be accessed as an array.
  316. :ref:`Transform2D <class_Transform2D>`
  317. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  318. 3x2 matrix used for 2D transforms.
  319. :ref:`Plane <class_Plane>`
  320. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  321. 3D Plane type in normalized form that contains a ``normal`` vector field
  322. and a ``d`` scalar distance.
  323. :ref:`Quat <class_Quat>`
  324. ^^^^^^^^^^^^^^^^^^^^^^^^
  325. Quaternion is a datatype used for representing a 3D rotation. It's
  326. useful for interpolating rotations.
  327. :ref:`AABB <class_AABB>`
  328. ^^^^^^^^^^^^^^^^^^^^^^^^
  329. Axis-aligned bounding box (or 3D box) contains 2 vectors fields: ``position``
  330. and ``size``. Alternatively contains an ``end`` field which is
  331. ``position+size``.
  332. :ref:`Basis <class_Basis>`
  333. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  334. 3x3 matrix used for 3D rotation and scale. It contains 3 vector fields
  335. (``x``, ``y`` and ``z``) and can also be accessed as an array of 3D
  336. vectors.
  337. :ref:`Transform <class_Transform>`
  338. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  339. 3D Transform contains a Basis field ``basis`` and a Vector3 field
  340. ``origin``.
  341. Engine built-in types
  342. ~~~~~~~~~~~~~~~~~~~~~
  343. :ref:`Color <class_Color>`
  344. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  345. Color data type contains ``r``, ``g``, ``b``, and ``a`` fields. It can
  346. also be accessed as ``h``, ``s``, and ``v`` for hue/saturation/value.
  347. :ref:`NodePath <class_NodePath>`
  348. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  349. Compiled path to a node used mainly in the scene system. It can be
  350. easily assigned to, and from, a String.
  351. :ref:`RID <class_RID>`
  352. ^^^^^^^^^^^^^^^^^^^^^^
  353. Resource ID (RID). Servers use generic RIDs to reference opaque data.
  354. :ref:`Object <class_Object>`
  355. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  356. Base class for anything that is not a built-in type.
  357. Container built-in types
  358. ~~~~~~~~~~~~~~~~~~~~~~~~
  359. :ref:`Array <class_Array>`
  360. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  361. Generic sequence of arbitrary object types, including other arrays or dictionaries (see below).
  362. The array can resize dynamically. Arrays are indexed starting from index ``0``.
  363. Starting with Godot 2.1, indices may be negative like in Python, to count from the end.
  364. ::
  365. var arr = []
  366. arr = [1, 2, 3]
  367. var b = arr[1] # This is 2
  368. var c = arr[arr.size() - 1] # This is 3
  369. var d = arr[-1] # Same as the previous line, but shorter
  370. arr[0] = "Hi!" # Replacing value 1 with "Hi"
  371. arr.append(4) # Array is now ["Hi", 2, 3, 4]
  372. GDScript arrays are allocated linearly in memory for speed.
  373. Large arrays (more than tens of thousands of elements) may however cause
  374. memory fragmentation. If this is a concern special types of
  375. arrays are available. These only accept a single data type. They avoid memory
  376. fragmentation and also use less memory but are atomic and tend to run slower than generic
  377. arrays. They are therefore only recommended to use for large data sets:
  378. - :ref:`PoolByteArray <class_PoolByteArray>`: An array of bytes (integers from 0 to 255).
  379. - :ref:`PoolIntArray <class_PoolIntArray>`: An array of integers.
  380. - :ref:`PoolRealArray <class_PoolRealArray>`: An array of floats.
  381. - :ref:`PoolStringArray <class_PoolStringArray>`: An array of strings.
  382. - :ref:`PoolVector2Array <class_PoolVector2Array>`: An array of :ref:`Vector2 <class_Vector2>` objects.
  383. - :ref:`PoolVector3Array <class_PoolVector3Array>`: An array of :ref:`Vector3 <class_Vector3>` objects.
  384. - :ref:`PoolColorArray <class_PoolColorArray>`: An array of :ref:`Color <class_Color>` objects.
  385. :ref:`Dictionary <class_Dictionary>`
  386. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  387. Associative container which contains values referenced by unique keys.
  388. ::
  389. var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
  390. d["Hi!"] = 0
  391. d = {
  392. 22: "value",
  393. "some_key": 2,
  394. "other_key": [2, 3, 4],
  395. "more_key": "Hello"
  396. }
  397. Lua-style table syntax is also supported. Lua-style uses ``=`` instead of ``:``
  398. and doesn't use quotes to mark string keys (making for slightly less to write).
  399. Note however that like any GDScript identifier, keys written in this form cannot
  400. start with a digit.
  401. ::
  402. var d = {
  403. test22 = "value",
  404. some_key = 2,
  405. other_key = [2, 3, 4],
  406. more_key = "Hello"
  407. }
  408. To add a key to an existing dictionary, access it like an existing key and
  409. assign to it::
  410. var d = {} # Create an empty Dictionary
  411. d.waiting = 14 # Add String "Waiting" as a key and assign the value 14 to it
  412. d[4] = "hello" # Add integer `4` as a key and assign the String "hello" as its value
  413. d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it
  414. Data
  415. ----
  416. Variables
  417. ~~~~~~~~~
  418. Variables can exist as class members or local to functions. They are
  419. created with the ``var`` keyword and may, optionally, be assigned a
  420. value upon initialization.
  421. ::
  422. var a # Data type is null by default
  423. var b = 5
  424. var c = 3.8
  425. var d = b + c # Variables are always initialized in order
  426. Constants
  427. ~~~~~~~~~
  428. Constants are similar to variables, but must be constants or constant
  429. expressions and must be assigned on initialization.
  430. ::
  431. const A = 5
  432. const B = Vector2(20, 20)
  433. const C = 10 + 20 # Constant expression
  434. const D = Vector2(20, 30).x # Constant expression: 20
  435. const E = [1, 2, 3, 4][0] # Constant expression: 1
  436. const F = sin(20) # sin() can be used in constant expressions
  437. const G = x + 20 # Invalid; this is not a constant expression!
  438. Enums
  439. ^^^^^
  440. Enums are basically a shorthand for constants, and are pretty useful if you
  441. want to assign consecutive integers to some constant.
  442. If you pass a name to the enum, it would also put all the values inside a
  443. constant dictionary of that name.
  444. ::
  445. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  446. # Is the same as:
  447. const TILE_BRICK = 0
  448. const TILE_FLOOR = 1
  449. const TILE_SPIKE = 2
  450. const TILE_TELEPORT = 3
  451. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  452. # Is the same as:
  453. const STATE_IDLE = 0
  454. const STATE_JUMP = 5
  455. const STATE_SHOOT = 6
  456. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  457. Functions
  458. ~~~~~~~~~
  459. Functions always belong to a `class <Classes_>`_. The scope priority for
  460. variable look-up is: local → class member → global. The ``self`` variable is
  461. always available and is provided as an option for accessing class members, but
  462. is not always required (and should *not* be sent as the function's first
  463. argument, unlike Python).
  464. ::
  465. func my_function(a, b):
  466. print(a)
  467. print(b)
  468. return a + b # Return is optional; without it null is returned
  469. A function can ``return`` at any point. The default return value is ``null``.
  470. Referencing Functions
  471. ^^^^^^^^^^^^^^^^^^^^^
  472. Contrary to Python, functions are *not* first class objects in GDScript. This
  473. means they cannot be stored in variables, passed as an argument to another
  474. function or be returned from other functions. This is for performance reasons.
  475. To reference a function by name at runtime, (e.g. to store it in a variable, or
  476. pass it to another function as an argument) one must use the ``call`` or
  477. ``funcref`` helpers::
  478. # Call a function by name in one step
  479. my_node.call("my_function", args)
  480. # Store a function reference
  481. var my_func = funcref(my_node, "my_function")
  482. # Call stored function reference
  483. my_func.call_func(args)
  484. Remember that default functions like ``_init``, and most
  485. notifications such as ``_enter_tree``, ``_exit_tree``, ``_process``,
  486. ``_physics_process``, etc. are called in all base classes automatically.
  487. So there is only a need to call the function explicitly when overloading
  488. them in some way.
  489. Static functions
  490. ^^^^^^^^^^^^^^^^
  491. A function can be declared static. When a function is static it has no
  492. access to the instance member variables or ``self``. This is mainly
  493. useful to make libraries of helper functions:
  494. ::
  495. static func sum2(a, b):
  496. return a + b
  497. Statements and control flow
  498. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  499. Statements are standard and can be assignments, function calls, control
  500. flow structures, etc (see below). ``;`` as a statement separator is
  501. entirely optional.
  502. if/else/elif
  503. ^^^^^^^^^^^^
  504. Simple conditions are created by using the ``if``/``else``/``elif`` syntax.
  505. Parenthesis around conditions are allowed, but not required. Given the
  506. nature of the tab-based indentation, ``elif`` can be used instead of
  507. ``else``/``if`` to maintain a level of indentation.
  508. ::
  509. if [expression]:
  510. statement(s)
  511. elif [expression]:
  512. statement(s)
  513. else:
  514. statement(s)
  515. Short statements can be written on the same line as the condition::
  516. if 1 + 1 == 2: return 2 + 2
  517. else:
  518. var x = 3 + 3
  519. return x
  520. Sometimes you might want to assign a different initial value based on a
  521. boolean expression. In this case ternary-if expressions come in handy::
  522. var x = [value] if [expression] else [value]
  523. y += 3 if y < 10 else -1
  524. while
  525. ^^^^^
  526. Simple loops are created by using ``while`` syntax. Loops can be broken
  527. using ``break`` or continued using ``continue``:
  528. ::
  529. while [expression]:
  530. statement(s)
  531. for
  532. ^^^
  533. To iterate through a range, such as an array or table, a *for* loop is
  534. used. When iterating over an array, the current array element is stored in
  535. the loop variable. When iterating over a dictionary, the *index* is stored
  536. in the loop variable.
  537. ::
  538. for x in [5, 7, 11]:
  539. statement # Loop iterates 3 times with x as 5, then 7 and finally 11
  540. var dict = {"a": 0, "b": 1, "c": 2}
  541. for i in dict:
  542. print(dict[i])
  543. for i in range(3):
  544. statement # Similar to [0, 1, 2] but does not allocate an array
  545. for i in range(1,3):
  546. statement # Similar to [1, 2] but does not allocate an array
  547. for i in range(2,8,2):
  548. statement # Similar to [2, 4, 6] but does not allocate an array
  549. for c in "Hello":
  550. print(c) # Iterate through all characters in a String, print every letter on new line
  551. match
  552. ^^^^^
  553. A ``match`` statement is used to branch execution of a program.
  554. It's the equivalent of the ``switch`` statement found in many other languages but offers some additional features.
  555. Basic syntax:
  556. ::
  557. match [expression]:
  558. [pattern](s):
  559. [block]
  560. [pattern](s):
  561. [block]
  562. [pattern](s):
  563. [block]
  564. **Crash-course for people who are familiar to switch statements**:
  565. 1. Replace ``switch`` with ``match``
  566. 2. Remove ``case``
  567. 3. Remove any ``break``'s. If you don't want to ``break`` by default you can use ``continue`` for a fallthrough.
  568. 4. Change ``default`` to a single underscore.
  569. **Control flow**:
  570. The patterns are matched from top to bottom.
  571. If a pattern matches, the corresponding block will be executed. After that, the execution continues below the ``match`` statement.
  572. If you want to have a fallthrough you can use ``continue`` to stop execution in the current block and check the ones below it.
  573. There are 6 pattern types:
  574. - constant pattern
  575. constant primitives, like numbers and strings ::
  576. match x:
  577. 1:
  578. print("We are number one!")
  579. 2:
  580. print("Two are better than one!")
  581. "test":
  582. print("Oh snap! It's a string!")
  583. - variable pattern
  584. matches the contents of a variable/enum ::
  585. match typeof(x):
  586. TYPE_FLOAT:
  587. print("float")
  588. TYPE_STRING:
  589. print("text")
  590. TYPE_ARRAY:
  591. print("array")
  592. - wildcard pattern
  593. This pattern matches everything. It's written as a single underscore.
  594. It can be used as the equivalent of the ``default`` in a ``switch`` statement in other languages. ::
  595. match x:
  596. 1:
  597. print("It's one!")
  598. 2:
  599. print("It's one times two!")
  600. _:
  601. print("It's not 1 or 2. I don't care tbh.")
  602. - binding pattern
  603. A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name.
  604. It's especially useful in array and dictionary patterns. ::
  605. match x:
  606. 1:
  607. print("It's one!")
  608. 2:
  609. print("It's one times two!")
  610. var new_var:
  611. print("It's not 1 or 2, it's ", new_var)
  612. - array pattern
  613. matches an array. Every single element of the array pattern is a pattern itself so you can nest them.
  614. The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern don't match.
  615. **Open-ended array**: An array can be bigger than the pattern by making the last subpattern ``..``
  616. Every subpattern has to be comma separated. ::
  617. match x:
  618. []:
  619. print("Empty array")
  620. [1, 3, "test", null]:
  621. print("Very specific array")
  622. [var start, _, "test"]:
  623. print("First element is ", start, ", and the last is \"test\"")
  624. [42, ..]:
  625. print("Open ended array")
  626. - dictionary pattern
  627. Works in the same way as the array pattern. Every key has to be a constant pattern.
  628. The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern don't match.
  629. **Open-ended dictionary**: A dictionary can be bigger than the pattern by making the last subpattern ``..``
  630. Every subpattern has to be comma separated.
  631. If you don't specify a value, then only the existence of the key is checked.
  632. A value pattern is separated from the key pattern with a ``:`` ::
  633. match x:
  634. {}:
  635. print("Empty dict")
  636. {"name": "Dennis"}:
  637. print("The name is Dennis")
  638. {"name": "Dennis", "age": var age}:
  639. print("Dennis is ", age, " years old.")
  640. {"name", "age"}:
  641. print("Has a name and an age, but it's not Dennis :(")
  642. {"key": "godotisawesome", ..}:
  643. print("I only checked for one entry and ignored the rest")
  644. Multipatterns:
  645. You can also specify multiple patterns separated by a comma. These patterns aren't allowed to have any bindings in them. ::
  646. match x:
  647. 1, 2, 3:
  648. print("It's 1 - 3")
  649. "Sword", "Splash potion", "Fist":
  650. print("Yep, you've taken damage")
  651. Classes
  652. ~~~~~~~
  653. By default, the body of a script file is an unnamed class and it can
  654. only be referenced externally as a resource or file. Class syntax is
  655. meant to be compact and can only contain member variables or
  656. functions. Static functions are allowed, but not static members (this is
  657. in the spirit of thread safety, since scripts can be initialized in
  658. separate threads without the user knowing). In the same way, member
  659. variables (including arrays and dictionaries) are initialized every time
  660. an instance is created.
  661. Below is an example of a class file.
  662. ::
  663. # Saved as a file named myclass.gd
  664. var a = 5
  665. func print_value_of_a():
  666. print(a)
  667. Inheritance
  668. ^^^^^^^^^^^
  669. A class (stored as a file) can inherit from
  670. - A global class
  671. - Another class file
  672. - An inner class inside another class file.
  673. Multiple inheritance is not allowed.
  674. Inheritance uses the ``extends`` keyword:
  675. ::
  676. # Inherit/extend a globally available class
  677. extends SomeClass
  678. # Inherit/extend a named class file
  679. extends "somefile.gd"
  680. # Inherit/extend an inner class in another file
  681. extends "somefile.gd".SomeInnerClass
  682. To check if a given instance inherits from a given class
  683. the ``is`` keyword can be used:
  684. ::
  685. # Cache the enemy class
  686. const Enemy = preload("enemy.gd")
  687. # [...]
  688. # Use 'is' to check inheritance
  689. if (entity is Enemy):
  690. entity.apply_damage()
  691. To call a function in a *base class* (i.e. one ``extend``-ed in your current class),
  692. prepend ``.`` to the function name:
  693. ::
  694. .basefunc(args)
  695. This is especially useful because functions in extending classes replace
  696. functions with the same name in their base classes. So if you still want
  697. to call them, you can use ``.`` like the ``super`` keyword in other languages:
  698. ::
  699. func some_func(x):
  700. .some_func(x) # Calls same function on the parent class
  701. Class Constructor
  702. ^^^^^^^^^^^^^^^^^
  703. The class constructor, called on class instantiation, is named ``_init``.
  704. As mentioned earlier, the constructors of parent classes are called automatically when
  705. inheriting a class. So there is usually no need to call ``._init()`` explicitly.
  706. If a parent constructor takes arguments, they are passed like this:
  707. ::
  708. func _init(args).(parent_args):
  709. pass
  710. Inner classes
  711. ^^^^^^^^^^^^^
  712. A class file can contain inner classes. Inner classes are defined using the
  713. ``class`` keyword. They are instanced using the ``ClassName.new()``
  714. function.
  715. ::
  716. # Inside a class file
  717. # An inner class in this class file
  718. class SomeInnerClass:
  719. var a = 5
  720. func print_value_of_a():
  721. print(a)
  722. # This is the constructor of the class file's main class
  723. func _init():
  724. var c = SomeInnerClass.new()
  725. c.print_value_of_a()
  726. Classes as resources
  727. ^^^^^^^^^^^^^^^^^^^^
  728. Classes stored as files are treated as :ref:`resources <class_GDScript>`. They
  729. must be loaded from disk to access them in other classes. This is done using
  730. either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
  731. class resource is done by calling the ``new`` function on the class object::
  732. # Load the class resource when calling load()
  733. var my_class = load("myclass.gd")
  734. # Preload the class only once at compile time
  735. const MyClass = preload("myclass.gd")
  736. func _init():
  737. var a = MyClass.new()
  738. a.some_function()
  739. Exports
  740. ~~~~~~~
  741. Class members can be exported. This means their value gets saved along
  742. with the resource (e.g. the :ref:`scene <class_PackedScene>`) they're attached
  743. to. They will also be available for editing in the property editor. Exporting
  744. is done by using the ``export`` keyword::
  745. extends Button
  746. export var number = 5 # Value will be saved and visible in the property editor
  747. An exported variable must be initialized to a constant expression or have an
  748. export hint in the form of an argument to the export keyword (see below).
  749. One of the fundamental benefits of exporting member variables is to have
  750. them visible and editable in the editor. This way artists and game designers
  751. can modify values that later influence how the program runs. For this, a
  752. special export syntax is provided.
  753. ::
  754. # If the exported value assigns a constant or constant expression,
  755. # the type will be inferred and used in the editor
  756. export var number = 5
  757. # Export can take a basic data type as an argument which will be
  758. # used in the editor
  759. export(int) var number
  760. # Export can also take a resource type to use as a hint
  761. export(Texture) var character_face
  762. export(PackedScene) var scene_file
  763. # Integers and strings hint enumerated values
  764. # Editor will enumerate as 0, 1 and 2
  765. export(int, "Warrior", "Magician", "Thief") var character_class
  766. # Editor will enumerate with string names
  767. export(String, "Rebecca", "Mary", "Leah") var character_name
  768. # Named enum values
  769. # Editor will enumerate as THING_1, THING_2, ANOTHER_THING
  770. enum NamedEnum {THING_1, THING_2, ANOTHER_THING = -1}
  771. export (NamedEnum) var x
  772. # Strings as paths
  773. # String is a path to a file
  774. export(String, FILE) var f
  775. # String is a path to a directory
  776. export(String, DIR) var f
  777. # String is a path to a file, custom filter provided as hint
  778. export(String, FILE, "*.txt") var f
  779. # Using paths in the global filesystem is also possible,
  780. # but only in tool scripts (see further below)
  781. # String is a path to a PNG file in the global filesystem
  782. export(String, FILE, GLOBAL, "*.png") var tool_image
  783. # String is a path to a directory in the global filesystem
  784. export(String, DIR, GLOBAL) var tool_dir
  785. # The MULTILINE setting tells the editor to show a large input
  786. # field for editing over multiple lines
  787. export(String, MULTILINE) var text
  788. # Limiting editor input ranges
  789. # Allow integer values from 0 to 20
  790. export(int, 20) var i
  791. # Allow integer values from -10 to 20
  792. export(int, -10, 20) var j
  793. # Allow floats from -10 to 20, with a step of 0.2
  794. export(float, -10, 20, 0.2) var k
  795. # Allow values y = exp(x) where y varies between 100 and 1000
  796. # while snapping to steps of 20. The editor will present a
  797. # slider for easily editing the value.
  798. export(float, EXP, 100, 1000, 20) var l
  799. # Floats with easing hint
  800. # Display a visual representation of the ease() function
  801. # when editing
  802. export(float, EASE) var transition_speed
  803. # Colors
  804. # Color given as Red-Green-Blue value
  805. export(Color, RGB) var col # Color is RGB
  806. # Color given as Red-Green-Blue-Alpha value
  807. export(Color, RGBA) var col # Color is RGBA
  808. # Another node in the scene can be exported too
  809. export(NodePath) var node
  810. It must be noted that even if the script is not being run while at the
  811. editor, the exported properties are still editable (see below for
  812. "tool").
  813. Exporting bit flags
  814. ^^^^^^^^^^^^^^^^^^^
  815. Integers used as bit flags can store multiple ``true``/``false`` (boolean)
  816. values in one property. By using the export hint ``int, FLAGS``, they
  817. can be set from the editor:
  818. ::
  819. # Individually edit the bits of an integer
  820. export(int, FLAGS) var spell_elements = ELEMENT_WIND | ELEMENT_WATER
  821. Restricting the flags to a certain number of named flags is also
  822. possible. The syntax is similar to the enumeration syntax:
  823. ::
  824. # Set any of the given flags from the editor
  825. export(int, FLAGS, "Fire", "Water", "Earth", "Wind") var spell_elements = 0
  826. In this example, ``Fire`` has value 1, ``Water`` has value 2, ``Earth``
  827. has value 4 and ``Wind`` corresponds to value 8. Usually, constants
  828. should be defined accordingly (e.g. ``const ELEMENT_WIND = 8`` and so
  829. on).
  830. Using bit flags requires some understanding of bitwise operations. If in
  831. doubt, boolean variables should be exported instead.
  832. Exporting arrays
  833. ^^^^^^^^^^^^^^^^
  834. Exporting arrays works but with an important caveat: While regular
  835. arrays are created local to every class instance, exported arrays are *shared*
  836. between all instances. This means that editing them in one instance will
  837. cause them to change in all other instances. Exported arrays can have
  838. initializers, but they must be constant expressions.
  839. ::
  840. # Exported array, shared between all instances.
  841. # Default value must be a constant expression.
  842. export var a=[1,2,3]
  843. # Typed arrays also work, only initialized empty:
  844. export var vector3s = PoolVector3Array()
  845. export var strings = PoolStringArray()
  846. # Regular array, created local for every instance.
  847. # Default value can include run-time values, but can't
  848. # be exported.
  849. var b = [a,2,3]
  850. Setters/getters
  851. ~~~~~~~~~~~~~~~
  852. It is often useful to know when a class' member variable changes for
  853. whatever reason. It may also be desired to encapsulate its access in some way.
  854. For this, GDScript provides a *setter/getter* syntax using the ``setget`` keyword.
  855. It is used directly after a variable definition:
  856. ::
  857. var variable = value setget setterfunc, getterfunc
  858. Whenever the value of ``variable`` is modified by an *external* source
  859. (i.e. not from local usage in the class), the *setter* function (``setterfunc`` above)
  860. will be called. This happens *before* the value is changed. The *setter* must decide what to do
  861. with the new value. Vice-versa, when ``variable`` is accessed, the *getter* function
  862. (``getterfunc`` above) must ``return`` the desired value. Below is an example:
  863. ::
  864. var myvar setget my_var_set, my_var_get
  865. func my_var_set(new_value):
  866. my_var = new_value
  867. func my_var_get():
  868. return my_var # Getter must return a value
  869. Either of the *setter* or *getter* functions can be omitted:
  870. ::
  871. # Only a setter
  872. var my_var = 5 setget myvar_set
  873. # Only a getter (note the comma)
  874. var my_var = 5 setget ,myvar_get
  875. Get/Setters are especially useful when exporting variables to editor in tool
  876. scripts or plugins, for validating input.
  877. As said *local* access will *not* trigger the setter and getter. Here is an
  878. illustration of this:
  879. ::
  880. func _init():
  881. # Does not trigger setter/getter
  882. my_integer = 5
  883. print(my_integer)
  884. # Does trigger setter/getter
  885. self.my_integer = 5
  886. print(self.my_integer)
  887. Tool mode
  888. ~~~~~~~~~
  889. Scripts, by default, don't run inside the editor and only the exported
  890. properties can be changed. In some cases it is desired that they do run
  891. inside the editor (as long as they don't execute game code or manually
  892. avoid doing so). For this, the ``tool`` keyword exists and must be
  893. placed at the top of the file:
  894. ::
  895. tool
  896. extends Button
  897. func _ready():
  898. print("Hello")
  899. Memory management
  900. ~~~~~~~~~~~~~~~~~
  901. If a class inherits from :ref:`class_Reference`, then instances will be
  902. freed when no longer in use. No garbage collector exists, just
  903. reference counting. By default, all classes that don't define
  904. inheritance extend **Reference**. If this is not desired, then a class
  905. must inherit :ref:`class_Object` manually and must call instance.free(). To
  906. avoid reference cycles that can't be freed, a ``weakref`` function is
  907. provided for creating weak references.
  908. Signals
  909. ~~~~~~~
  910. It is often desired to send a notification that something happened in an
  911. instance. GDScript supports creation of built-in Godot signals.
  912. Declaring a signal in GDScript is easy using the `signal` keyword.
  913. ::
  914. # No arguments
  915. signal your_signal_name
  916. # With arguments
  917. signal your_signal_name_with_args(a, b)
  918. These signals can be connected in the editor or from code like regular signals.
  919. Take the instance of a class where the signal was
  920. declared and connect it to the method of another instance:
  921. ::
  922. func _callback_no_args():
  923. print("Got callback!")
  924. func _callback_args(a,b):
  925. print("Got callback with args! a: ", a, " and b: ", b)
  926. func _at_some_func():
  927. instance.connect("your_signal_name", self, "_callback_no_args")
  928. instance.connect("your_signal_name_with_args", self, "_callback_args")
  929. It is also possible to bind arguments to a signal that lacks them with
  930. your custom values:
  931. ::
  932. func _at_some_func():
  933. instance.connect("your_signal_name", self, "_callback_args", [22, "hello"])
  934. This is useful when a signal from many objects is connected to a
  935. single callback and the sender must be identified:
  936. ::
  937. func _button_pressed(which):
  938. print("Button was pressed: ", which.get_name())
  939. func _ready():
  940. for b in get_node("buttons").get_children():
  941. b.connect("pressed", self, "_button_pressed",[b])
  942. Finally, emitting a custom signal is done by using the
  943. Object.emit_signal method:
  944. ::
  945. func _at_some_func():
  946. emit_signal("your_signal_name")
  947. emit_signal("your_signal_name_with_args", 55, 128)
  948. some_instance.emit_signal("some_signal")
  949. Coroutines with yield
  950. ~~~~~~~~~~~~~~~~~~~~~
  951. GDScript offers support for `coroutines <https://en.wikipedia.org/wiki/Coroutine>`_
  952. via the ``yield`` built-in function. Calling ``yield()`` will
  953. immediately return from the current function, with the current frozen
  954. state of the same function as the return value. Calling ``resume`` on
  955. this resulting object will continue execution and return whatever the
  956. function returns. Once resumed the state object becomes invalid. Here is
  957. an example:
  958. ::
  959. func my_func():
  960. print("Hello")
  961. yield()
  962. print("world")
  963. func _ready():
  964. var y = my_func()
  965. # Function state saved in 'y'
  966. print("my dear")
  967. y.resume()
  968. # 'y' resumed and is now an invalid state
  969. Will print:
  970. ::
  971. Hello
  972. my dear
  973. world
  974. It is also possible to pass values between yield() and resume(), for
  975. example:
  976. ::
  977. func my_func():
  978. print("Hello")
  979. print(yield())
  980. return "cheers!"
  981. func _ready():
  982. var y = my_func()
  983. # Function state saved in 'y'
  984. print(y.resume("world"))
  985. # 'y' resumed and is now an invalid state
  986. Will print:
  987. ::
  988. Hello
  989. world
  990. cheers!
  991. Coroutines & signals
  992. ^^^^^^^^^^^^^^^^^^^^
  993. The real strength of using ``yield`` is when combined with signals.
  994. ``yield`` can accept two parameters, an object and a signal. When the
  995. signal is received, execution will recommence. Here are some examples:
  996. ::
  997. # Resume execution the next frame
  998. yield(get_tree(), "idle_frame")
  999. # Resume execution when animation is done playing:
  1000. yield(get_node("AnimationPlayer"), "finished")
  1001. # Wait 5 seconds, then resume execution
  1002. yield(get_tree().create_timer(5.0), "timeout")
  1003. Onready keyword
  1004. ~~~~~~~~~~~~~~~
  1005. When using nodes, it's common to desire to keep references to parts
  1006. of the scene in a variable. As scenes are only warranted to be
  1007. configured when entering the active scene tree, the sub-nodes can only
  1008. be obtained when a call to Node._ready() is made.
  1009. ::
  1010. var my_label
  1011. func _ready():
  1012. my_label = get_node("MyLabel")
  1013. This can get a little cumbersome, especially when nodes and external
  1014. references pile up. For this, GDScript has the ``onready`` keyword, that
  1015. defers initialization of a member variable until _ready is called. It
  1016. can replace the above code with a single line:
  1017. ::
  1018. onready var my_label = get_node("MyLabel")
  1019. Assert keyword
  1020. ~~~~~~~~~~~~~~
  1021. The ``assert`` keyword can be used to check conditions in debug builds.
  1022. These assertions are ignored in non-debug builds.
  1023. ::
  1024. # Check that i is 0
  1025. assert(i == 0)