gdscript_basics.rst 63 KB

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