gdscript_basics.rst 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  1. .. _doc_gdscript:
  2. GDScript reference
  3. ==================
  4. :ref:`GDScript<doc_gdscript>` is a high-level, `object-oriented
  5. <https://en.wikipedia.org/wiki/Object-oriented_programming>`_, `imperative
  6. <https://en.wikipedia.org/wiki/Imperative_programming>`_, and `gradually typed
  7. <https://en.wikipedia.org/wiki/Gradual_typing>`_ programming language built for Godot.
  8. *GDScript* is a high-level, dynamically typed programming language used to
  9. create content. It uses an indentation-based syntax similar to languages like
  10. `Python <https://en.wikipedia.org/wiki/Python_%28programming_language%29>`_.
  11. Its goal is to be optimized for and tightly integrated with Godot Engine,
  12. allowing great flexibility for content creation and integration.
  13. GDScript is entirely independent from Python and is not based on it.
  14. History
  15. -------
  16. .. note::
  17. Documentation about GDScript's history has been moved to the
  18. :ref:`Frequently Asked Questions <doc_faq_what_is_gdscript>`.
  19. Example of GDScript
  20. -------------------
  21. Some people can learn better by taking a look at the syntax, so
  22. here's an example of how GDScript looks.
  23. ::
  24. # Everything after "#" is a comment.
  25. # A file is a class!
  26. # (optional) icon to show in the editor dialogs:
  27. @icon("res://path/to/optional/icon.svg")
  28. # (optional) class definition:
  29. class_name MyClass
  30. # Inheritance:
  31. extends BaseClass
  32. # Member variables.
  33. var a = 5
  34. var s = "Hello"
  35. var arr = [1, 2, 3]
  36. var dict = {"key": "value", 2: 3}
  37. var other_dict = {key = "value", other_key = 2}
  38. var typed_var: int
  39. var inferred_type := "String"
  40. # Constants.
  41. const ANSWER = 42
  42. const THE_NAME = "Charly"
  43. # Enums.
  44. enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
  45. enum Named {THING_1, THING_2, ANOTHER_THING = -1}
  46. # Built-in vector types.
  47. var v2 = Vector2(1, 2)
  48. var v3 = Vector3(1, 2, 3)
  49. # Functions.
  50. func some_function(param1, param2, param3):
  51. const local_const = 5
  52. if param1 < local_const:
  53. print(param1)
  54. elif param2 > 5:
  55. print(param2)
  56. else:
  57. print("Fail!")
  58. for i in range(20):
  59. print(i)
  60. while param2 != 0:
  61. param2 -= 1
  62. match param3:
  63. 3:
  64. print("param3 is 3!")
  65. _:
  66. print("param3 is not 3!")
  67. var local_var = param1 + 3
  68. return local_var
  69. # Functions override functions with the same name on the base/super class.
  70. # If you still want to call them, use "super":
  71. func something(p1, p2):
  72. super(p1, p2)
  73. # It's also possible to call another function in the super class:
  74. func other_something(p1, p2):
  75. super.something(p1, p2)
  76. # Inner class
  77. class Something:
  78. var a = 10
  79. # Constructor
  80. func _init():
  81. print("Constructed!")
  82. var lv = Something.new()
  83. print(lv.a)
  84. If you have previous experience with statically typed languages such as
  85. C, C++, or C# but never used a dynamically typed one before, it is advised you
  86. read this tutorial: :ref:`doc_gdscript_more_efficiently`.
  87. Language
  88. --------
  89. In the following, an overview is given to GDScript. Details, such as which
  90. methods are available to arrays or other objects, should be looked up in
  91. the linked class descriptions.
  92. Identifiers
  93. ~~~~~~~~~~~
  94. Any string that restricts itself to alphabetic characters (``a`` to ``z`` and
  95. ``A`` to ``Z``), digits (``0`` to ``9``) and ``_`` qualifies as an identifier.
  96. Additionally, identifiers must not begin with a digit. Identifiers are
  97. case-sensitive (``foo`` is different from ``FOO``).
  98. Identifiers may also contain most Unicode characters part of
  99. `UAX#31 <https://www.unicode.org/reports/tr31/>`__. This allows you to use
  100. identifier names written in languages other than English. Unicode characters
  101. that are considered "confusable" for ASCII characters and emoji are not allowed
  102. in identifiers.
  103. Keywords
  104. ~~~~~~~~
  105. The following is the list of keywords supported by the language. Since
  106. keywords are reserved words (tokens), they can't be used as identifiers.
  107. Operators (like ``in``, ``not``, ``and`` or ``or``) and names of built-in types
  108. as listed in the following sections are also reserved.
  109. Keywords are defined in the `GDScript tokenizer <https://github.com/godotengine/godot/blob/master/modules/gdscript/gdscript_tokenizer.cpp>`_
  110. in case you want to take a look under the hood.
  111. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  112. | Keyword | Description |
  113. +============+===================================================================================================================================================+
  114. | if | See `if/else/elif`_. |
  115. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  116. | elif | See `if/else/elif`_. |
  117. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  118. | else | See `if/else/elif`_. |
  119. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  120. | for | See for_. |
  121. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  122. | while | See while_. |
  123. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  124. | match | See match_. |
  125. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  126. | break | Exits the execution of the current ``for`` or ``while`` loop. |
  127. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  128. | continue | Immediately skips to the next iteration of the ``for`` or ``while`` loop. |
  129. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  130. | pass | Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions. |
  131. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  132. | return | Returns a value from a function. |
  133. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  134. | class | Defines a class. |
  135. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  136. | class_name | Defines the script as a globally accessible class with the specified name. |
  137. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  138. | extends | Defines what class to extend with the current class. |
  139. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  140. | is | Tests whether a variable extends a given class, or is of a given built-in type. |
  141. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  142. | in | Tests whether a value is within a string, list, range, dictionary, or node. When used with ``for``, it iterates through them instead of testing. |
  143. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  144. | as | Cast the value to a given type if possible. |
  145. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  146. | self | Refers to current class instance. |
  147. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  148. | signal | Defines a signal. |
  149. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  150. | func | Defines a function. |
  151. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  152. | static | Defines a static function. Static member variables are not allowed. |
  153. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  154. | const | Defines a constant. |
  155. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  156. | enum | Defines an enum. |
  157. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  158. | var | Defines a variable. |
  159. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  160. | breakpoint | Editor helper for debugger breakpoints. |
  161. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  162. | preload | Preloads a class or variable. See `Classes as resources`_. |
  163. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  164. | await | Waits for a signal or a coroutine to finish. See `Awaiting for signals`_. |
  165. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  166. | yield | Previously used for coroutines. Kept as keyword for transition. |
  167. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  168. | assert | Asserts a condition, logs error on failure. Ignored in non-debug builds. See `Assert keyword`_. |
  169. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  170. | void | Used to represent that a function does not return any value. |
  171. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  172. | PI | PI constant. |
  173. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  174. | TAU | TAU constant. |
  175. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  176. | INF | Infinity constant. Used for comparisons and as result of calculations. |
  177. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  178. | NAN | NAN (not a number) constant. Used as impossible result from calculations. |
  179. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  180. Operators
  181. ~~~~~~~~~
  182. The following is the list of supported operators and their precedence.
  183. +--------------------------------------------------------------------------------+-------------------------------------------+
  184. | **Operator** | **Description** |
  185. +================================================================================+===========================================+
  186. | ``x[index]`` | Subscription (highest priority) |
  187. +--------------------------------------------------------------------------------+-------------------------------------------+
  188. | ``x.attribute`` | Attribute reference |
  189. +--------------------------------------------------------------------------------+-------------------------------------------+
  190. | ``foo()`` | Function call |
  191. +--------------------------------------------------------------------------------+-------------------------------------------+
  192. | ``is`` | Instance type checker |
  193. +--------------------------------------------------------------------------------+-------------------------------------------+
  194. | ``**`` | Power operator |
  195. | | |
  196. | | Multiplies value by itself ``x`` times, |
  197. | | similar to calling ``pow`` built-in |
  198. | | function |
  199. +--------------------------------------------------------------------------------+-------------------------------------------+
  200. | ``~`` | Bitwise NOT |
  201. +--------------------------------------------------------------------------------+-------------------------------------------+
  202. | ``-x`` | Negative / Unary negation |
  203. +--------------------------------------------------------------------------------+-------------------------------------------+
  204. | ``*`` ``/`` ``%`` | Multiplication / Division / Remainder |
  205. | | |
  206. | | These operators have the same behavior |
  207. | | as C++. Integer division is truncated |
  208. | | rather than returning a fractional |
  209. | | number, and the % operator is only |
  210. | | available for ints (``fmod`` for floats), |
  211. | | and is additionally used for Format |
  212. | | Strings |
  213. +--------------------------------------------------------------------------------+-------------------------------------------+
  214. | ``+`` | Addition / Concatenation of arrays |
  215. +--------------------------------------------------------------------------------+-------------------------------------------+
  216. | ``-`` | Subtraction |
  217. +--------------------------------------------------------------------------------+-------------------------------------------+
  218. | ``<<`` ``>>`` | Bit shifting |
  219. +--------------------------------------------------------------------------------+-------------------------------------------+
  220. | ``&`` | Bitwise AND |
  221. +--------------------------------------------------------------------------------+-------------------------------------------+
  222. | ``^`` | Bitwise XOR |
  223. +--------------------------------------------------------------------------------+-------------------------------------------+
  224. | ``|`` | Bitwise OR |
  225. +--------------------------------------------------------------------------------+-------------------------------------------+
  226. | ``<`` ``>`` ``==`` ``!=`` ``>=`` ``<=`` | Comparisons |
  227. +--------------------------------------------------------------------------------+-------------------------------------------+
  228. | ``in`` | Inclusion checker (when used with |
  229. | | control flow keywords or in a |
  230. | | standalone expression). |
  231. | | |
  232. | | Content iterator (when used with the |
  233. | | for_ keyword). |
  234. +--------------------------------------------------------------------------------+-------------------------------------------+
  235. | ``not`` | Boolean NOT |
  236. +--------------------------------------------------------------------------------+-------------------------------------------+
  237. | ``and`` | Boolean AND |
  238. +--------------------------------------------------------------------------------+-------------------------------------------+
  239. | ``or`` | Boolean OR |
  240. +--------------------------------------------------------------------------------+-------------------------------------------+
  241. | ``if x else`` | Ternary if/else |
  242. +--------------------------------------------------------------------------------+-------------------------------------------+
  243. | ``as`` | Type casting |
  244. +--------------------------------------------------------------------------------+-------------------------------------------+
  245. | ``=`` ``+=`` ``-=`` ``*=`` ``/=`` ``%=`` ``**=`` ``&=`` ``|=`` ``<<=`` ``>>=`` | Assignment (lowest priority) |
  246. +--------------------------------------------------------------------------------+-------------------------------------------+
  247. Literals
  248. ~~~~~~~~
  249. +--------------------------+-------------------------------------------+
  250. | **Literal** | **Type** |
  251. +--------------------------+-------------------------------------------+
  252. | ``45`` | Base 10 integer |
  253. +--------------------------+-------------------------------------------+
  254. | ``0x8f51`` | Base 16 (hexadecimal) integer |
  255. +--------------------------+-------------------------------------------+
  256. | ``0b101010`` | Base 2 (binary) integer |
  257. +--------------------------+-------------------------------------------+
  258. | ``3.14``, ``58.1e-10`` | Floating-point number (real) |
  259. +--------------------------+-------------------------------------------+
  260. | ``"Hello"``, ``'Hi'`` | Strings |
  261. +--------------------------+-------------------------------------------+
  262. | ``"""Hello"""`` | Multiline string |
  263. +--------------------------+-------------------------------------------+
  264. | ``&"name"`` | :ref:`StringName <class_StringName>` |
  265. +--------------------------+-------------------------------------------+
  266. | ``^"Node/Label"`` | :ref:`NodePath <class_NodePath>` |
  267. +--------------------------+-------------------------------------------+
  268. | ``$NodePath`` | Shorthand for ``get_node("NodePath")`` |
  269. +--------------------------+-------------------------------------------+
  270. | ``%UniqueNode`` | Shorthand for ``get_node("%UniqueNode")`` |
  271. +--------------------------+-------------------------------------------+
  272. Integers and floats can have their numbers separated with ``_`` to make them more readable.
  273. The following ways to write numbers are all valid::
  274. 12_345_678 # Equal to 12345678.
  275. 3.141_592_7 # Equal to 3.1415927.
  276. 0x8080_0000_ffff # Equal to 0x80800000ffff.
  277. 0b11_00_11_00 # Equal to 0b11001100.
  278. Annotations
  279. ~~~~~~~~~~~
  280. There are some special tokens in GDScript that act like keywords but are not,
  281. they are *annotations* instead. Every annotation start with the ``@`` character
  282. and is specified by a name. A detailed description and example for each annotation
  283. can be found inside the :ref:`GDScript class reference <class_@GDScript>`.
  284. Annotations affect how the script is treated by external tools and usually don't
  285. change the behavior.
  286. For instance, you can use it to export a value to the editor::
  287. @export_range(1, 100, 1, "or_greater")
  288. var ranged_var: int = 50
  289. For more information about exporting properties, read the :ref:`GDScript exports <doc_gdscript_exports>`
  290. article.
  291. Annotations can be specified one per line or all in the same line. They affect
  292. the next statement that isn't an annotation. Annotations can have arguments sent
  293. between parentheses and separated by commas.
  294. Both of these are the same::
  295. @onready
  296. @export_node_path(TextEdit, LineEdit)
  297. var input_field
  298. @onready @export_node_path(TextEdit, LineEdit) var input_field
  299. .. _doc_gdscript_onready_annotation:
  300. `@onready` annotation
  301. ~~~~~~~~~~~~~~~~~~~~~
  302. When using nodes, it's common to desire to keep references to parts
  303. of the scene in a variable. As scenes are only warranted to be
  304. configured when entering the active scene tree, the sub-nodes can only
  305. be obtained when a call to ``Node._ready()`` is made.
  306. ::
  307. var my_label
  308. func _ready():
  309. my_label = get_node("MyLabel")
  310. This can get a little cumbersome, especially when nodes and external
  311. references pile up. For this, GDScript has the ``@onready`` annotation, that
  312. defers initialization of a member variable until ``_ready()`` is called. It
  313. can replace the above code with a single line::
  314. @onready var my_label = get_node("MyLabel")
  315. Comments
  316. ~~~~~~~~
  317. Anything from a ``#`` to the end of the line is ignored and is
  318. considered a comment.
  319. ::
  320. # This is a comment.
  321. .. _doc_gdscript_builtin_types:
  322. Line continuation
  323. ~~~~~~~~~~~~~~~~~
  324. A line of code in GDScript can be continued on the next line by using a backslash
  325. (``\``). Add one at the end of a line and the code on the next line will act like
  326. it's where the backslash is. Here is an example:
  327. ::
  328. var a = 1 + \
  329. 2
  330. A line can be continued multiple times like this:
  331. ::
  332. var a = 1 + \
  333. 4 + \
  334. 10 + \
  335. 4
  336. Built-in types
  337. --------------
  338. Built-in types are stack-allocated. They are passed as values. This means a copy
  339. is created on each assignment or when passing them as arguments to functions.
  340. The only exceptions are ``Array``\ s and ``Dictionaries``, which are passed by
  341. reference so they are shared. (Packed arrays such as ``PackedByteArray`` are still
  342. passed as values.)
  343. Basic built-in types
  344. ~~~~~~~~~~~~~~~~~~~~
  345. A variable in GDScript can be assigned to several built-in types.
  346. null
  347. ^^^^
  348. ``null`` is an empty data type that contains no information and can not
  349. be assigned any other value.
  350. :ref:`bool <class_bool>`
  351. ^^^^^^^^^^^^^^^^^^^^^^^^
  352. Short for "boolean", it can only contain ``true`` or ``false``.
  353. :ref:`int <class_int>`
  354. ^^^^^^^^^^^^^^^^^^^^^^
  355. Short for "integer", it stores whole numbers (positive and negative).
  356. It is stored as a 64-bit value, equivalent to "int64_t" in C++.
  357. :ref:`float <class_float>`
  358. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  359. Stores real numbers, including decimals, using floating-point values.
  360. It is stored as a 64-bit value, equivalent to "double" in C++.
  361. Note: Currently, data structures such as Vector2, Vector3, and
  362. PackedFloat32Array store 32-bit single-precision "float" values.
  363. :ref:`String <class_String>`
  364. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  365. A sequence of characters in `Unicode format <https://en.wikipedia.org/wiki/Unicode>`_.
  366. Strings can contain the following escape sequences:
  367. +---------------------+---------------------------------+
  368. | **Escape sequence** | **Expands to** |
  369. +---------------------+---------------------------------+
  370. | ``\n`` | Newline (line feed) |
  371. +---------------------+---------------------------------+
  372. | ``\t`` | Horizontal tab character |
  373. +---------------------+---------------------------------+
  374. | ``\r`` | Carriage return |
  375. +---------------------+---------------------------------+
  376. | ``\a`` | Alert (beep/bell) |
  377. +---------------------+---------------------------------+
  378. | ``\b`` | Backspace |
  379. +---------------------+---------------------------------+
  380. | ``\f`` | Formfeed page break |
  381. +---------------------+---------------------------------+
  382. | ``\v`` | Vertical tab character |
  383. +---------------------+---------------------------------+
  384. | ``\"`` | Double quote |
  385. +---------------------+---------------------------------+
  386. | ``\'`` | Single quote |
  387. +---------------------+---------------------------------+
  388. | ``\\`` | Backslash |
  389. +---------------------+---------------------------------+
  390. | ``\uXXXX`` | Unicode codepoint ``XXXX`` |
  391. | | (hexadecimal, case-insensitive) |
  392. +---------------------+---------------------------------+
  393. Also, using ``\`` followed by a newline inside a string will allow you to continue it in the next line, without
  394. inserting a newline character in the string itself.
  395. GDScript also supports :ref:`doc_gdscript_printf`.
  396. :ref:`StringName <class_StringName>`
  397. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  398. An immutable string that allows only one instance of each name. They are slower to
  399. create and may result in waiting for locks when multithreading. In exchange, they're
  400. very fast to compare, which makes them good candidates for dictionary keys.
  401. :ref:`NodePath <class_NodePath>`
  402. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  403. A pre-parsed path to a node or a node property. They are useful to interact with
  404. the tree to get a node, or affecting properties like with :ref:`Tweens <class_Tween>`.
  405. Vector built-in types
  406. ~~~~~~~~~~~~~~~~~~~~~
  407. :ref:`Vector2 <class_Vector2>`
  408. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  409. 2D vector type containing ``x`` and ``y`` fields. Can also be
  410. accessed as an array.
  411. :ref:`Vector2i <class_Vector2i>`
  412. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  413. Same as a Vector2 but the components are integers. Useful for representing
  414. items in a 2D grid.
  415. :ref:`Rect2 <class_Rect2>`
  416. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  417. 2D Rectangle type containing two vectors fields: ``position`` and ``size``.
  418. Also contains an ``end`` field which is ``position + size``.
  419. :ref:`Vector3 <class_Vector3>`
  420. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  421. 3D vector type containing ``x``, ``y`` and ``z`` fields. This can also
  422. be accessed as an array.
  423. :ref:`Vector3i <class_Vector3i>`
  424. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  425. Same as Vector3 but the components are integers. Can be use for indexing items
  426. in a 3D grid.
  427. :ref:`Transform2D <class_Transform2D>`
  428. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  429. 3×2 matrix used for 2D transforms.
  430. :ref:`Plane <class_Plane>`
  431. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  432. 3D Plane type in normalized form that contains a ``normal`` vector field
  433. and a ``d`` scalar distance.
  434. :ref:`Quaternion <class_Quaternion>`
  435. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  436. Quaternion is a datatype used for representing a 3D rotation. It's
  437. useful for interpolating rotations.
  438. :ref:`AABB <class_AABB>`
  439. ^^^^^^^^^^^^^^^^^^^^^^^^
  440. Axis-aligned bounding box (or 3D box) contains 2 vectors fields: ``position``
  441. and ``size``. Also contains an ``end`` field which is
  442. ``position + size``.
  443. :ref:`Basis <class_Basis>`
  444. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  445. 3x3 matrix used for 3D rotation and scale. It contains 3 vector fields
  446. (``x``, ``y`` and ``z``) and can also be accessed as an array of 3D
  447. vectors.
  448. :ref:`Transform3D <class_Transform3D>`
  449. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  450. 3D Transform contains a Basis field ``basis`` and a Vector3 field
  451. ``origin``.
  452. Engine built-in types
  453. ~~~~~~~~~~~~~~~~~~~~~
  454. :ref:`Color <class_Color>`
  455. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  456. Color data type contains ``r``, ``g``, ``b``, and ``a`` fields. It can
  457. also be accessed as ``h``, ``s``, and ``v`` for hue/saturation/value.
  458. :ref:`NodePath <class_NodePath>`
  459. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  460. Compiled path to a node used mainly in the scene system. It can be
  461. easily assigned to, and from, a String.
  462. :ref:`RID <class_RID>`
  463. ^^^^^^^^^^^^^^^^^^^^^^
  464. Resource ID (RID). Servers use generic RIDs to reference opaque data.
  465. :ref:`Object <class_Object>`
  466. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  467. Base class for anything that is not a built-in type.
  468. Container built-in types
  469. ~~~~~~~~~~~~~~~~~~~~~~~~
  470. :ref:`Array <class_Array>`
  471. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  472. Generic sequence of arbitrary object types, including other arrays or dictionaries (see below).
  473. The array can resize dynamically. Arrays are indexed starting from index ``0``.
  474. Negative indices count from the end.
  475. ::
  476. var arr = []
  477. arr = [1, 2, 3]
  478. var b = arr[1] # This is 2.
  479. var c = arr[arr.size() - 1] # This is 3.
  480. var d = arr[-1] # Same as the previous line, but shorter.
  481. arr[0] = "Hi!" # Replacing value 1 with "Hi!".
  482. arr.append(4) # Array is now ["Hi!", 2, 3, 4].
  483. GDScript arrays are allocated linearly in memory for speed.
  484. Large arrays (more than tens of thousands of elements) may however cause
  485. memory fragmentation. If this is a concern, special types of
  486. arrays are available. These only accept a single data type. They avoid memory
  487. fragmentation and use less memory, but are atomic and tend to run slower than generic
  488. arrays. They are therefore only recommended to use for large data sets:
  489. - :ref:`PackedByteArray <class_PackedByteArray>`: An array of bytes (integers from 0 to 255).
  490. - :ref:`PackedInt32Array <class_PackedInt32Array>`: An array of 32-bit integers.
  491. - :ref:`PackedInt64Array <class_PackedInt64Array>`: An array of 64-bit integers.
  492. - :ref:`PackedFloat32Array <class_PackedFloat32Array>`: An array of 32-bit floats.
  493. - :ref:`PackedFloat64Array <class_PackedFloat64Array>`: An array of 64-bit floats.
  494. - :ref:`PackedStringArray <class_PackedStringArray>`: An array of strings.
  495. - :ref:`PackedVector2Array <class_PackedVector2Array>`: An array of :ref:`Vector2 <class_Vector2>` objects.
  496. - :ref:`PackedVector3Array <class_PackedVector3Array>`: An array of :ref:`Vector3 <class_Vector3>` objects.
  497. - :ref:`PackedColorArray <class_PackedColorArray>`: An array of :ref:`Color <class_Color>` objects.
  498. :ref:`Dictionary <class_Dictionary>`
  499. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  500. Associative container which contains values referenced by unique keys.
  501. ::
  502. var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
  503. d["Hi!"] = 0
  504. d = {
  505. 22: "value",
  506. "some_key": 2,
  507. "other_key": [2, 3, 4],
  508. "more_key": "Hello"
  509. }
  510. Lua-style table syntax is also supported. Lua-style uses ``=`` instead of ``:``
  511. and doesn't use quotes to mark string keys (making for slightly less to write).
  512. However, keys written in this form can't start with a digit (like any GDScript
  513. identifier).
  514. ::
  515. var d = {
  516. test22 = "value",
  517. some_key = 2,
  518. other_key = [2, 3, 4],
  519. more_key = "Hello"
  520. }
  521. To add a key to an existing dictionary, access it like an existing key and
  522. assign to it::
  523. var d = {} # Create an empty Dictionary.
  524. d.waiting = 14 # Add String "waiting" as a key and assign the value 14 to it.
  525. d[4] = "hello" # Add integer 4 as a key and assign the String "hello" as its value.
  526. d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it.
  527. var test = 4
  528. # Prints "hello" by indexing the dictionary with a dynamic key.
  529. # This is not the same as `d.test`. The bracket syntax equivalent to
  530. # `d.test` is `d["test"]`.
  531. print(d[test])
  532. .. note::
  533. The bracket syntax can be used to access properties of any
  534. :ref:`class_Object`, not just Dictionaries. Keep in mind it will cause a
  535. script error when attempting to index a non-existing property. To avoid
  536. this, use the :ref:`Object.get() <class_Object_method_get>` and
  537. :ref:`Object.set() <class_Object_method_set>` methods instead.
  538. :ref:`Signal <class_Signal>`
  539. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  540. A signal is a message that can be emitted by an object to those who want to
  541. listen to it. The Signal type can be used for passing the emitter around.
  542. Signals are better used by getting them from actual objects, e.g. ``$Button.button_up``.
  543. :ref:`Callable <class_Callable>`
  544. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  545. Contains an object and a function, which is useful for passing functions as
  546. values (e.g. when connecting to signals).
  547. Getting a method as a member returns a callable. ``var x = $Sprite2D.rotate``
  548. will set the value of ``x`` to a callable with ``$Sprite2D`` as the object and
  549. ``rotate`` as the method.
  550. You can call it using the ``call`` method: ``x.call(PI)``.
  551. Data
  552. ----
  553. Variables
  554. ~~~~~~~~~
  555. Variables can exist as class members or local to functions. They are
  556. created with the ``var`` keyword and may, optionally, be assigned a
  557. value upon initialization.
  558. ::
  559. var a # Data type is 'null' by default.
  560. var b = 5
  561. var c = 3.8
  562. var d = b + c # Variables are always initialized in order.
  563. Variables can optionally have a type specification. When a type is specified,
  564. the variable will be forced to have always that same type, and trying to assign
  565. an incompatible value will raise an error.
  566. Types are specified in the variable declaration using a ``:`` (colon) symbol
  567. after the variable name, followed by the type.
  568. ::
  569. var my_vector2: Vector2
  570. var my_node: Node = Sprite2D.new()
  571. If the variable is initialized within the declaration, the type can be inferred, so
  572. it's possible to omit the type name::
  573. var my_vector2 := Vector2() # 'my_vector2' is of type 'Vector2'.
  574. var my_node := Sprite2D.new() # 'my_node' is of type 'Sprite2D'.
  575. Type inference is only possible if the assigned value has a defined type, otherwise
  576. it will raise an error.
  577. Valid types are:
  578. - Built-in types (Array, Vector2, int, String, etc.).
  579. - Engine classes (Node, Resource, Reference, etc.).
  580. - Constant names if they contain a script resource (``MyScript`` if you declared ``const MyScript = preload("res://my_script.gd")``).
  581. - Other classes in the same script, respecting scope (``InnerClass.NestedClass`` if you declared ``class NestedClass`` inside the ``class InnerClass`` in the same scope).
  582. - Script classes declared with the ``class_name`` keyword.
  583. - Autoloads registered as singletons.
  584. Casting
  585. ^^^^^^^
  586. Values assigned to typed variables must have a compatible type. If it's needed to
  587. coerce a value to be of a certain type, in particular for object types, you can
  588. use the casting operator ``as``.
  589. Casting between object types results in the same object if the value is of the
  590. same type or a subtype of the cast type.
  591. ::
  592. var my_node2D: Node2D
  593. my_node2D = $Sprite2D as Node2D # Works since Sprite2D is a subtype of Node2D.
  594. If the value is not a subtype, the casting operation will result in a ``null`` value.
  595. ::
  596. var my_node2D: Node2D
  597. my_node2D = $Button as Node2D # Results in 'null' since a Button is not a subtype of Node2D.
  598. For built-in types, they will be forcibly converted if possible, otherwise the
  599. engine will raise an error.
  600. ::
  601. var my_int: int
  602. my_int = "123" as int # The string can be converted to int.
  603. my_int = Vector2() as int # A Vector2 can't be converted to int, this will cause an error.
  604. Casting is also useful to have better type-safe variables when interacting with
  605. the scene tree::
  606. # Will infer the variable to be of type Sprite2D.
  607. var my_sprite := $Character as Sprite2D
  608. # Will fail if $AnimPlayer is not an AnimationPlayer, even if it has the method 'play()'.
  609. ($AnimPlayer as AnimationPlayer).play("walk")
  610. Constants
  611. ~~~~~~~~~
  612. Constants are values you cannot change when the game is running.
  613. Their value must be known at compile-time. Using the
  614. ``const`` keyword allows you to give a constant value a name. Trying to assign a
  615. value to a constant after it's declared will give you an error.
  616. We recommend using constants whenever a value is not meant to change.
  617. ::
  618. const A = 5
  619. const B = Vector2(20, 20)
  620. const C = 10 + 20 # Constant expression.
  621. const D = Vector2(20, 30).x # Constant expression: 20.
  622. const E = [1, 2, 3, 4][0] # Constant expression: 1.
  623. const F = sin(20) # 'sin()' can be used in constant expressions.
  624. const G = x + 20 # Invalid; this is not a constant expression!
  625. const H = A + 20 # Constant expression: 25 (`A` is a constant).
  626. Although the type of constants is inferred from the assigned value, it's also
  627. possible to add explicit type specification::
  628. const A: int = 5
  629. const B: Vector2 = Vector2()
  630. Assigning a value of an incompatible type will raise an error.
  631. You can also create constants inside a function, which is useful to name local
  632. magic values.
  633. .. note::
  634. Since objects, arrays and dictionaries are passed by reference, constants are "flat".
  635. This means that if you declare a constant array or dictionary, it can still
  636. be modified afterwards. They can't be reassigned with another value though.
  637. Enums
  638. ^^^^^
  639. Enums are basically a shorthand for constants, and are pretty useful if you
  640. want to assign consecutive integers to some constant.
  641. If you pass a name to the enum, it will put all the keys inside a constant
  642. dictionary of that name.
  643. .. important:: In Godot 3.1 and later, keys in a named enum are not registered
  644. as global constants. They should be accessed prefixed by the
  645. enum's name (``Name.KEY``); see an example below.
  646. ::
  647. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  648. # Is the same as:
  649. const TILE_BRICK = 0
  650. const TILE_FLOOR = 1
  651. const TILE_SPIKE = 2
  652. const TILE_TELEPORT = 3
  653. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  654. # Is the same as:
  655. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  656. # Access values with State.STATE_IDLE, etc.
  657. Functions
  658. ~~~~~~~~~
  659. Functions always belong to a `class <Classes_>`_. The scope priority for
  660. variable look-up is: local → class member → global. The ``self`` variable is
  661. always available and is provided as an option for accessing class members, but
  662. is not always required (and should *not* be sent as the function's first
  663. argument, unlike Python).
  664. ::
  665. func my_function(a, b):
  666. print(a)
  667. print(b)
  668. return a + b # Return is optional; without it 'null' is returned.
  669. A function can ``return`` at any point. The default return value is ``null``.
  670. If a function contains only one line of code, it can be written on one line::
  671. func square(a): return a * a
  672. func hello_world(): print("Hello World")
  673. func empty_function(): pass
  674. Functions can also have type specification for the arguments and for the return
  675. value. Types for arguments can be added in a similar way to variables::
  676. func my_function(a: int, b: String):
  677. pass
  678. If a function argument has a default value, it's possible to infer the type::
  679. func my_function(int_arg := 42, String_arg := "string"):
  680. pass
  681. The return type of the function can be specified after the arguments list using
  682. the arrow token (``->``)::
  683. func my_int_function() -> int:
  684. return 0
  685. Functions that have a return type **must** return a proper value. Setting the
  686. type as ``void`` means the function doesn't return anything. Void functions can
  687. return early with the ``return`` keyword, but they can't return any value.
  688. ::
  689. func void_function() -> void:
  690. return # Can't return a value.
  691. .. note:: Non-void functions must **always** return a value, so if your code has
  692. branching statements (such as an ``if``/``else`` construct), all the
  693. possible paths must have a return. E.g., if you have a ``return``
  694. inside an ``if`` block but not after it, the editor will raise an
  695. error because if the block is not executed, the function won't have a
  696. valid value to return.
  697. Referencing functions
  698. ^^^^^^^^^^^^^^^^^^^^^
  699. Functions are first-class items in terms of the :ref:`Callable <class_Callable>` object. Referencing a
  700. function by name without calling it will automatically generate the proper
  701. callable. This can be used to pass functions as arguments.
  702. ::
  703. func map(arr: Array, function: Callable) -> Array:
  704. var result = []
  705. for item in arr:
  706. result.push_back(function.call(item))
  707. return result
  708. func add1(value: int) -> int:
  709. return value + 1;
  710. func _ready() -> void:
  711. var my_array = [1, 2, 3]
  712. var plus_one = map(my_array, add1)
  713. print(plus_one) # Prints [2, 3, 4].
  714. .. note:: Callables **must** be called with the ``call`` method. You cannot use
  715. the ``()`` operator directly. This behavior is implemented to avoid
  716. performance issues on direct function calls.
  717. Lambda functions
  718. ^^^^^^^^^^^^^^^^
  719. Lambda functions allow you to declare functions that do not belong to a class. Instead a :ref:`Callable <class_Callable>` object is created and assigned to a variable directly.
  720. This can be useful to create Callables to pass around without polluting the class scope.
  721. ::
  722. var lambda = func(x): print(x)
  723. lambda.call(42) # Prints "42"
  724. Lambda functions can be named for debugging purposes::
  725. var lambda = func my_lambda(x):
  726. print(x)
  727. Lambda functions capture the local environment. Local variables are passed by value, so they won't be updated in the lambda if changed in the local function::
  728. var x = 42
  729. var my_lambda = func(): print(x)
  730. my_lambda.call() # Prints "42"
  731. x = "Hello"
  732. my_lambda.call() # Prints "42"
  733. .. note:: The values of the outer scope behave like constants. Therefore, if you declare an array or dictionary, it can still be modified afterwards.
  734. Static functions
  735. ^^^^^^^^^^^^^^^^
  736. A function can be declared static. When a function is static, it has no
  737. access to the instance member variables or ``self``. This is mainly
  738. useful to make libraries of helper functions::
  739. static func sum2(a, b):
  740. return a + b
  741. Lambdas cannot be declared static.
  742. Statements and control flow
  743. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  744. Statements are standard and can be assignments, function calls, control
  745. flow structures, etc (see below). ``;`` as a statement separator is
  746. entirely optional.
  747. Expressions
  748. ^^^^^^^^^^^
  749. Expressions are sequences of operators and their operands in orderly fashion. An expression by itself can be a
  750. statement too, though only calls are reasonable to use as statements since other expressions don't have side effects.
  751. Expressions return values that can be assigned to valid targets. Operands to some operator can be another
  752. expression. An assignment is not an expression and thus does not return any value.
  753. Here are some examples of expressions::
  754. 2 + 2 # Binary operation.
  755. -5 # Unary operation.
  756. "okay" if x > 4 else "not okay" # Ternary operation.
  757. x # Identifier representing variable or constant.
  758. x.a # Attribute access.
  759. x[4] # Subscript access.
  760. x > 2 or x < 5 # Comparisons and logic operators.
  761. x == y + 2 # Equality test.
  762. do_something() # Function call.
  763. [1, 2, 3] # Array definition.
  764. {A = 1, B = 2} # Dictionary definition.
  765. preload("res://icon.png") # Preload builtin function.
  766. self # Reference to current instance.
  767. Identifiers, attributes, and subscripts are valid assignment targets. Other expressions cannot be on the left side of
  768. an assignment.
  769. if/else/elif
  770. ^^^^^^^^^^^^
  771. Simple conditions are created by using the ``if``/``else``/``elif`` syntax.
  772. Parenthesis around conditions are allowed, but not required. Given the
  773. nature of the tab-based indentation, ``elif`` can be used instead of
  774. ``else``/``if`` to maintain a level of indentation.
  775. ::
  776. if (expression):
  777. statement(s)
  778. elif (expression):
  779. statement(s)
  780. else:
  781. statement(s)
  782. Short statements can be written on the same line as the condition::
  783. if 1 + 1 == 2: return 2 + 2
  784. else:
  785. var x = 3 + 3
  786. return x
  787. Sometimes, you might want to assign a different initial value based on a
  788. boolean expression. In this case, ternary-if expressions come in handy::
  789. var x = (value) if (expression) else (value)
  790. y += 3 if y < 10 else -1
  791. Ternary-if expressions can be nested to handle more than 2 cases. When nesting
  792. ternary-if expressions, it is recommended to wrap the complete expression over
  793. multiple lines to preserve readability::
  794. var count = 0
  795. var fruit = (
  796. "apple" if count == 2
  797. else "pear" if count == 1
  798. else "banana" if count == 0
  799. else "orange"
  800. )
  801. print(fruit) # banana
  802. # Alternative syntax with backslashes instead of parentheses (for multi-line expressions).
  803. # Less lines required, but harder to refactor.
  804. var fruit_alt = \
  805. "apple" if count == 2 \
  806. else "pear" if count == 1 \
  807. else "banana" if count == 0 \
  808. else "orange"
  809. print(fruit_alt) # banana
  810. You may also wish to check if a value is contained within something. You can
  811. use an ``if`` statement combined with the ``in`` operator to accomplish this::
  812. # Check if a letter is in a string.
  813. var text = "abc"
  814. if 'b' in text: print("The string contains b")
  815. # Check if a variable is contained within a node.
  816. if "varName" in get_parent(): print("varName is defined in parent!")
  817. while
  818. ^^^^^
  819. Simple loops are created by using ``while`` syntax. Loops can be broken
  820. using ``break`` or continued using ``continue`` (which skips to the next
  821. iteration of the loop without executing any further code in the current iteration):
  822. ::
  823. while (expression):
  824. statement(s)
  825. for
  826. ^^^
  827. To iterate through a range, such as an array or table, a *for* loop is
  828. used. When iterating over an array, the current array element is stored in
  829. the loop variable. When iterating over a dictionary, the *key* is stored
  830. in the loop variable.
  831. ::
  832. for x in [5, 7, 11]:
  833. statement # Loop iterates 3 times with 'x' as 5, then 7 and finally 11.
  834. var dict = {"a": 0, "b": 1, "c": 2}
  835. for i in dict:
  836. print(dict[i]) # Prints 0, then 1, then 2.
  837. for i in range(3):
  838. statement # Similar to [0, 1, 2] but does not allocate an array.
  839. for i in range(1, 3):
  840. statement # Similar to [1, 2] but does not allocate an array.
  841. for i in range(2, 8, 2):
  842. statement # Similar to [2, 4, 6] but does not allocate an array.
  843. for c in "Hello":
  844. print(c) # Iterate through all characters in a String, print every letter on new line.
  845. for i in 3:
  846. statement # Similar to range(3).
  847. for i in 2.2:
  848. statement # Similar to range(ceil(2.2)).
  849. If you want to assign values on an array as it is being iterated through, it
  850. is best to use ``for i in array.size()``.
  851. ::
  852. for i in array.size():
  853. array[i] = "Hello World"
  854. The loop variable is local to the for-loop and assigning to it will not change
  855. the value on the array. Objects passed by reference (such as nodes) can still
  856. be manipulated by calling methods on the loop variable.
  857. ::
  858. for string in string_array:
  859. string = "Hello World" # This has no effect
  860. for node in node_array:
  861. node.add_to_group("Cool_Group") # This has an effect
  862. match
  863. ^^^^^
  864. A ``match`` statement is used to branch execution of a program.
  865. It's the equivalent of the ``switch`` statement found in many other languages, but offers some additional features.
  866. Basic syntax::
  867. match (expression):
  868. [pattern](s):
  869. [block]
  870. [pattern](s):
  871. [block]
  872. [pattern](s):
  873. [block]
  874. **Crash-course for people who are familiar with switch statements**:
  875. 1. Replace ``switch`` with ``match``.
  876. 2. Remove ``case``.
  877. 3. Remove any ``break``\ s.
  878. 4. Change ``default`` to a single underscore.
  879. **Control flow**:
  880. The patterns are matched from top to bottom.
  881. If a pattern matches, the first corresponding block will be executed. After that, the execution continues below the ``match`` statement.
  882. There are 6 pattern types:
  883. - Constant pattern
  884. Constant primitives, like numbers and strings::
  885. match x:
  886. 1:
  887. print("We are number one!")
  888. 2:
  889. print("Two are better than one!")
  890. "test":
  891. print("Oh snap! It's a string!")
  892. - Variable pattern
  893. Matches the contents of a variable/enum::
  894. match typeof(x):
  895. TYPE_FLOAT:
  896. print("float")
  897. TYPE_STRING:
  898. print("text")
  899. TYPE_ARRAY:
  900. print("array")
  901. - Wildcard pattern
  902. This pattern matches everything. It's written as a single underscore.
  903. It can be used as the equivalent of the ``default`` in a ``switch`` statement in other languages::
  904. match x:
  905. 1:
  906. print("It's one!")
  907. 2:
  908. print("It's one times two!")
  909. _:
  910. print("It's not 1 or 2. I don't care to be honest.")
  911. - Binding pattern
  912. A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name.
  913. It's especially useful in array and dictionary patterns::
  914. match x:
  915. 1:
  916. print("It's one!")
  917. 2:
  918. print("It's one times two!")
  919. var new_var:
  920. print("It's not 1 or 2, it's ", new_var)
  921. - Array pattern
  922. Matches an array. Every single element of the array pattern is a pattern itself, so you can nest them.
  923. The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  924. **Open-ended array**: An array can be bigger than the pattern by making the last subpattern ``..``.
  925. Every subpattern has to be comma-separated.
  926. ::
  927. match x:
  928. []:
  929. print("Empty array")
  930. [1, 3, "test", null]:
  931. print("Very specific array")
  932. [var start, _, "test"]:
  933. print("First element is ", start, ", and the last is \"test\"")
  934. [42, ..]:
  935. print("Open ended array")
  936. - Dictionary pattern
  937. Works in the same way as the array pattern. Every key has to be a constant pattern.
  938. The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  939. **Open-ended dictionary**: A dictionary can be bigger than the pattern by making the last subpattern ``..``.
  940. Every subpattern has to be comma separated.
  941. If you don't specify a value, then only the existence of the key is checked.
  942. A value pattern is separated from the key pattern with a ``:``.
  943. ::
  944. match x:
  945. {}:
  946. print("Empty dict")
  947. {"name": "Dennis"}:
  948. print("The name is Dennis")
  949. {"name": "Dennis", "age": var age}:
  950. print("Dennis is ", age, " years old.")
  951. {"name", "age"}:
  952. print("Has a name and an age, but it's not Dennis :(")
  953. {"key": "godotisawesome", ..}:
  954. print("I only checked for one entry and ignored the rest")
  955. - Multiple patterns
  956. You can also specify multiple patterns separated by a comma. These patterns aren't allowed to have any bindings in them.
  957. ::
  958. match x:
  959. 1, 2, 3:
  960. print("It's 1 - 3")
  961. "Sword", "Splash potion", "Fist":
  962. print("Yep, you've taken damage")
  963. Classes
  964. ~~~~~~~
  965. By default, all script files are unnamed classes. In this case, you can only
  966. reference them using the file's path, using either a relative or an absolute
  967. path. For example, if you name a script file ``character.gd``::
  968. # Inherit from 'Character.gd'.
  969. extends "res://path/to/character.gd"
  970. # Load character.gd and create a new node instance from it.
  971. var Character = load("res://path/to/character.gd")
  972. var character_node = Character.new()
  973. .. _doc_gdscript_basics_class_name:
  974. Registering named classes
  975. ~~~~~~~~~~~~~~~~~~~~~~~~~
  976. You can give your class a name to register it as a new type in Godot's
  977. editor. For that, you use the ``class_name`` keyword. You can optionally use
  978. the ``@icon`` annotation with a path to an image, to use it as an icon. Your
  979. class will then appear with its new icon in the editor::
  980. # Item.gd
  981. @icon("res://interface/icons/item.png")
  982. class_name Item
  983. extends Node
  984. .. image:: img/class_name_editor_register_example.png
  985. Here's a class file example:
  986. ::
  987. # Saved as a file named 'character.gd'.
  988. class_name Character
  989. var health = 5
  990. func print_health():
  991. print(health)
  992. func print_this_script_three_times():
  993. print(get_script())
  994. print(ResourceLoader.load("res://character.gd"))
  995. print(Character)
  996. If you want to use ``extends`` too, you can keep both on the same line::
  997. class_name MyNode extends Node
  998. .. note:: Godot's class syntax is compact: it can only contain member variables or
  999. functions. You can use static functions, but not static member variables. In the
  1000. same way, the engine initializes variables every time you create an instance,
  1001. and this includes arrays and dictionaries. This is in the spirit of thread
  1002. safety, since scripts can be initialized in separate threads without the user
  1003. knowing.
  1004. Inheritance
  1005. ^^^^^^^^^^^
  1006. A class (stored as a file) can inherit from:
  1007. - A global class.
  1008. - Another class file.
  1009. - An inner class inside another class file.
  1010. Multiple inheritance is not allowed.
  1011. Inheritance uses the ``extends`` keyword::
  1012. # Inherit/extend a globally available class.
  1013. extends SomeClass
  1014. # Inherit/extend a named class file.
  1015. extends "somefile.gd"
  1016. # Inherit/extend an inner class in another file.
  1017. extends "somefile.gd".SomeInnerClass
  1018. .. note::
  1019. If inheritance is not explicitly defined, the class will default to inheriting
  1020. :ref:`class_RefCounted`.
  1021. To check if a given instance inherits from a given class,
  1022. the ``is`` keyword can be used::
  1023. # Cache the enemy class.
  1024. const Enemy = preload("enemy.gd")
  1025. # [...]
  1026. # Use 'is' to check inheritance.
  1027. if entity is Enemy:
  1028. entity.apply_damage()
  1029. To call a function in a *super class* (i.e. one ``extend``-ed in your current
  1030. class), use the ``super`` keyword::
  1031. super(args)
  1032. This is especially useful because functions in extending classes replace
  1033. functions with the same name in their super classes. If you still want to
  1034. call them, you can use ``super``::
  1035. func some_func(x):
  1036. super(x) # Calls the same function on the super class.
  1037. If you need to call a different function from the super class, you can specify
  1038. the function name with the attribute operator::
  1039. func overriding():
  1040. return 0 # This overrides the method in the base class.
  1041. func dont_override():
  1042. return super.overriding() # This calls the method as defined in the base class.
  1043. Class constructor
  1044. ^^^^^^^^^^^^^^^^^
  1045. The class constructor, called on class instantiation, is named ``_init``. If you
  1046. want to call the base class constructor, you can also use the ``super`` syntax.
  1047. Note that every class has an implicit constructor that it's always called
  1048. (defining the default values of class variables). ``super`` is used to call the
  1049. explicit constructor::
  1050. func _init(arg):
  1051. super("some_default", arg) # Call the custom base constructor.
  1052. This is better explained through examples. Consider this scenario::
  1053. # State.gd (inherited class).
  1054. var entity = null
  1055. var message = null
  1056. func _init(e=null):
  1057. entity = e
  1058. func enter(m):
  1059. message = m
  1060. # Idle.gd (inheriting class).
  1061. extends "State.gd"
  1062. func _init(e=null, m=null):
  1063. super(e)
  1064. # Do something with 'e'.
  1065. message = m
  1066. There are a few things to keep in mind here:
  1067. 1. If the inherited class (``State.gd``) defines a ``_init`` constructor that takes
  1068. arguments (``e`` in this case), then the inheriting class (``Idle.gd``) *must*
  1069. define ``_init`` as well and pass appropriate parameters to ``_init`` from ``State.gd``.
  1070. 2. ``Idle.gd`` can have a different number of arguments than the base class ``State.gd``.
  1071. 3. In the example above, ``e`` passed to the ``State.gd`` constructor is the same ``e`` passed
  1072. in to ``Idle.gd``.
  1073. 4. If ``Idle.gd``'s ``_init`` constructor takes 0 arguments, it still needs to pass some value
  1074. to the ``State.gd`` base class, even if it does nothing. This brings us to the fact that you
  1075. can pass expressions to the base constructor as well, not just variables, e.g.::
  1076. # Idle.gd
  1077. func _init():
  1078. super(5)
  1079. Inner classes
  1080. ^^^^^^^^^^^^^
  1081. A class file can contain inner classes. Inner classes are defined using the
  1082. ``class`` keyword. They are instanced using the ``ClassName.new()``
  1083. function.
  1084. ::
  1085. # Inside a class file.
  1086. # An inner class in this class file.
  1087. class SomeInnerClass:
  1088. var a = 5
  1089. func print_value_of_a():
  1090. print(a)
  1091. # This is the constructor of the class file's main class.
  1092. func _init():
  1093. var c = SomeInnerClass.new()
  1094. c.print_value_of_a()
  1095. .. _doc_gdscript_classes_as_resources:
  1096. Classes as resources
  1097. ^^^^^^^^^^^^^^^^^^^^
  1098. Classes stored as files are treated as :ref:`resources <class_GDScript>`. They
  1099. must be loaded from disk to access them in other classes. This is done using
  1100. either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
  1101. class resource is done by calling the ``new`` function on the class object::
  1102. # Load the class resource when calling load().
  1103. var MyClass = load("myclass.gd")
  1104. # Preload the class only once at compile time.
  1105. const MyClass = preload("myclass.gd")
  1106. func _init():
  1107. var a = MyClass.new()
  1108. a.some_function()
  1109. Exports
  1110. ~~~~~~~
  1111. .. note::
  1112. Documentation about exports has been moved to :ref:`doc_gdscript_exports`.
  1113. .. _doc_gdscript_basics_setters_getters:
  1114. Properties (setters and getters)
  1115. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1116. Sometimes, you want a class' member variable to do more than just hold data and actually perform
  1117. some validation or computation whenever its value change. It may also be desired to
  1118. encapsulate its access in some way.
  1119. For this, GDScript provides a special syntax to define properties using the ``set`` and ``get``
  1120. keywords after a variable declaration. Then you can define a code block that will be executed
  1121. when the variable is accessed or assigned.
  1122. Example::
  1123. var milliseconds: int = 0
  1124. var seconds: int:
  1125. get:
  1126. return milliseconds / 1000
  1127. set(value):
  1128. milliseconds = value * 1000
  1129. Using the variable name inside its own setter or getter will directly access the underlying member, so it
  1130. won't generate infinite recursion and saves you from explicitly declaring another variable::
  1131. signal changed(new_value)
  1132. var warns_when_changed = "some value":
  1133. get:
  1134. return warns_when_changed
  1135. set(value):
  1136. changed.emit(value)
  1137. warns_when_changed = value
  1138. This backing member variable is not created if you don't use it.
  1139. .. note::
  1140. Unlike ``setget`` in previous Godot versions, the properties setter and getter are **always** called,
  1141. even when accessed inside the same class (with or without prefixing with ``self.``). This makes the behavior
  1142. consistent. If you need direct access to the value, use another variable for direct access and make the property
  1143. code use that name.
  1144. In case you want to split the code from the variable declaration or you need to share the code across multiple properties,
  1145. you can use a different notation to use existing class functions::
  1146. var my_prop:
  1147. get = get_my_prop, set = set_my_prop
  1148. This can also be done in the same line.
  1149. .. _doc_gdscript_tool_mode:
  1150. Tool mode
  1151. ~~~~~~~~~
  1152. By default, scripts don't run inside the editor and only the exported
  1153. properties can be changed. In some cases, it is desired that they do run
  1154. inside the editor (as long as they don't execute game code or manually
  1155. avoid doing so). For this, the ``@tool`` annotation exists and must be
  1156. placed at the top of the file::
  1157. @tool
  1158. extends Button
  1159. func _ready():
  1160. print("Hello")
  1161. See :ref:`doc_running_code_in_the_editor` for more information.
  1162. .. warning:: Be cautious when freeing nodes with ``queue_free()`` or ``free()``
  1163. in a tool script (especially the script's owner itself). As tool
  1164. scripts run their code in the editor, misusing them may lead to
  1165. crashing the editor.
  1166. .. _doc_gdscript_basics_memory_management:
  1167. Memory management
  1168. ~~~~~~~~~~~~~~~~~
  1169. Godot implements reference counting to free certain instances that are no longer
  1170. used, instead of a garbage collector, or requiring purely manual management.
  1171. Any instance of the :ref:`class_RefCounted` class (or any class that inherits
  1172. it, such as :ref:`class_Resource`) will be freed automatically when no longer
  1173. in use. For an instance of any class that is not a :ref:`class_RefCounted`
  1174. (such as :ref:`class_Node` or the base :ref:`class_Object` type), it will
  1175. remain in memory until it is deleted with ``free()`` (or ``queue_free()``
  1176. for Nodes).
  1177. .. note::
  1178. If a :ref:`class_Node` is deleted via ``free()`` or ``queue_free()``,
  1179. all of its children will also recursively be deleted.
  1180. To avoid reference cycles that can't be freed, a :ref:`class_WeakRef`
  1181. function is provided for creating weak references, which allow access
  1182. to the object without preventing a :ref:`class_RefCounted` from freeing.
  1183. Here is an example:
  1184. ::
  1185. extends Node
  1186. var my_file_ref
  1187. func _ready():
  1188. var f = File.new()
  1189. my_file_ref = weakref(f)
  1190. # the File class inherits RefCounted, so it will be freed when not in use
  1191. # the WeakRef will not prevent f from being freed when other_node is finished
  1192. other_node.use_file(f)
  1193. func _this_is_called_later():
  1194. var my_file = my_file_ref.get_ref()
  1195. if my_file:
  1196. my_file.close()
  1197. Alternatively, when not using references, the
  1198. ``is_instance_valid(instance)`` can be used to check if an object has been
  1199. freed.
  1200. .. _doc_gdscript_signals:
  1201. Signals
  1202. ~~~~~~~
  1203. Signals are a tool to emit messages from an object that other objects can react
  1204. to. To create custom signals for a class, use the ``signal`` keyword.
  1205. ::
  1206. extends Node
  1207. # A signal named health_depleted.
  1208. signal health_depleted
  1209. .. note::
  1210. Signals are a `Callback
  1211. <https://en.wikipedia.org/wiki/Callback_(computer_programming)>`_
  1212. mechanism. They also fill the role of Observers, a common programming
  1213. pattern. For more information, read the `Observer tutorial
  1214. <https://gameprogrammingpatterns.com/observer.html>`_ in the
  1215. Game Programming Patterns ebook.
  1216. You can connect these signals to methods the same way you connect built-in
  1217. signals of nodes like :ref:`class_Button` or :ref:`class_RigidBody3D`.
  1218. In the example below, we connect the ``health_depleted`` signal from a
  1219. ``Character`` node to a ``Game`` node. When the ``Character`` node emits the
  1220. signal, the game node's ``_on_Character_health_depleted`` is called::
  1221. # Game.gd
  1222. func _ready():
  1223. var character_node = get_node('Character')
  1224. character_node.health_depleted.connect(_on_Character_health_depleted)
  1225. func _on_Character_health_depleted():
  1226. get_tree().reload_current_scene()
  1227. You can emit as many arguments as you want along with a signal.
  1228. Here is an example where this is useful. Let's say we want a life bar on screen
  1229. to react to health changes with an animation, but we want to keep the user
  1230. interface separate from the player in our scene tree.
  1231. In our ``Character.gd`` script, we define a ``health_changed`` signal and emit
  1232. it with :ref:`Signal.emit() <class_Signal_method_emit>`, and from
  1233. a ``Game`` node higher up our scene tree, we connect it to the ``Lifebar`` using
  1234. the :ref:`Signal.connect() <class_Signal_method_connect>` method::
  1235. # Character.gd
  1236. ...
  1237. signal health_changed
  1238. func take_damage(amount):
  1239. var old_health = health
  1240. health -= amount
  1241. # We emit the health_changed signal every time the
  1242. # character takes damage.
  1243. health_changed.emit(old_health, health)
  1244. ...
  1245. ::
  1246. # Lifebar.gd
  1247. # Here, we define a function to use as a callback when the
  1248. # character's health_changed signal is emitted.
  1249. ...
  1250. func _on_Character_health_changed(old_value, new_value):
  1251. if old_value > new_value:
  1252. progress_bar.modulate = Color.RED
  1253. else:
  1254. progress_bar.modulate = Color.GREEN
  1255. # Imagine that `animate` is a user-defined function that animates the
  1256. # bar filling up or emptying itself.
  1257. progress_bar.animate(old_value, new_value)
  1258. ...
  1259. In the ``Game`` node, we get both the ``Character`` and ``Lifebar`` nodes, then
  1260. connect the character, that emits the signal, to the receiver, the ``Lifebar``
  1261. node in this case.
  1262. ::
  1263. # Game.gd
  1264. func _ready():
  1265. var character_node = get_node('Character')
  1266. var lifebar_node = get_node('UserInterface/Lifebar')
  1267. character_node.health_changed.connect(lifebar_node._on_Character_health_changed)
  1268. This allows the ``Lifebar`` to react to health changes without coupling it to
  1269. the ``Character`` node.
  1270. You can write optional argument names in parentheses after the signal's
  1271. definition::
  1272. # Defining a signal that forwards two arguments.
  1273. signal health_changed(old_value, new_value)
  1274. These arguments show up in the editor's node dock, and Godot can use them to
  1275. generate callback functions for you. However, you can still emit any number of
  1276. arguments when you emit signals; it's up to you to emit the correct values.
  1277. .. image:: img/gdscript_basics_signals_node_tab_1.png
  1278. GDScript can bind an array of values to connections between a signal
  1279. and a method. When the signal is emitted, the callback method receives
  1280. the bound values. These bound arguments are unique to each connection,
  1281. and the values will stay the same.
  1282. You can use this array of values to add extra constant information to the
  1283. connection if the emitted signal itself doesn't give you access to all the data
  1284. that you need.
  1285. Building on the example above, let's say we want to display a log of the damage
  1286. taken by each character on the screen, like ``Player1 took 22 damage.``. The
  1287. ``health_changed`` signal doesn't give us the name of the character that took
  1288. damage. So when we connect the signal to the in-game console, we can add the
  1289. character's name in the binds array argument::
  1290. # Game.gd
  1291. func _ready():
  1292. var character_node = get_node('Character')
  1293. var battle_log_node = get_node('UserInterface/BattleLog')
  1294. character_node.health_changed.connect(battle_log_node._on_Character_health_changed, [character_node.name])
  1295. Our ``BattleLog`` node receives each element in the binds array as an extra argument::
  1296. # BattleLog.gd
  1297. func _on_Character_health_changed(old_value, new_value, character_name):
  1298. if not new_value <= old_value:
  1299. return
  1300. var damage = old_value - new_value
  1301. label.text += character_name + " took " + str(damage) + " damage."
  1302. Awaiting for signals
  1303. ~~~~~~~~~~~~~~~~~~~~
  1304. The ``await`` keyword can be used to create `coroutines <https://en.wikipedia.org/wiki/Coroutine>`_
  1305. which waits until a signal is emitted before continuing execution. Using the ``await`` keyword with a signal or a
  1306. call to a function that is also a coroutine will immediately return the control to the caller. When the signal is
  1307. emitted (or the called coroutine finishes), it will resume execution from the point on where it stopped.
  1308. For example, to stop execution until the user presses a button, you can do something like this::
  1309. func wait_confirmation():
  1310. print("Prompting user")
  1311. await $Button.button_up # Waits for the button_up signal from Button node.
  1312. print("User confirmed")
  1313. return true
  1314. In this case, the ``wait_confirmation`` becomes a coroutine, which means that the caller also needs to await for it::
  1315. func request_confirmation():
  1316. print("Will ask the user")
  1317. var confirmed = await wait_confirmation()
  1318. if confirmed:
  1319. print("User confirmed")
  1320. else:
  1321. print("User cancelled")
  1322. Note that requesting a coroutine's return value without ``await`` will trigger an error::
  1323. func wrong():
  1324. var confirmed = wait_confirmation() # Will give an error.
  1325. However, if you don't depend on the result, you can just call it asynchronously, which won't stop execution and won't
  1326. make the current function a coroutine::
  1327. func okay():
  1328. wait_confirmation()
  1329. print("This will be printed immediately, before the user press the button.")
  1330. If you use await with an expression that isn't a signal nor a coroutine, the value will be returned immediately and the
  1331. function won't give the control back to the caller::
  1332. func no_wait():
  1333. var x = await get_five()
  1334. print("This doesn't make this function a coroutine.")
  1335. func get_five():
  1336. return 5
  1337. This also means that returning a signal from a function that isn't a coroutine will make the caller await on that signal::
  1338. func get_signal():
  1339. return $Button.button_up
  1340. func wait_button():
  1341. await get_signal()
  1342. print("Button was pressed")
  1343. .. note:: Unlike ``yield`` in previous Godot versions, you cannot obtain the function state object.
  1344. This is done to ensure type safety.
  1345. With this type safety in place, a function cannot say that it returns an ``int`` while it actually returns a function state object
  1346. during runtime.
  1347. Assert keyword
  1348. ~~~~~~~~~~~~~~
  1349. The ``assert`` keyword can be used to check conditions in debug builds. These
  1350. assertions are ignored in non-debug builds. This means that the expression
  1351. passed as argument won't be evaluated in a project exported in release mode.
  1352. Due to this, assertions must **not** contain expressions that have
  1353. side effects. Otherwise, the behavior of the script would vary
  1354. depending on whether the project is run in a debug build.
  1355. ::
  1356. # Check that 'i' is 0. If 'i' is not 0, an assertion error will occur.
  1357. assert(i == 0)
  1358. When running a project from the editor, the project will be paused if an
  1359. assertion error occurs.
  1360. You can optionally pass a custom error message to be shown if the assertion
  1361. fails::
  1362. assert(enemy_power < 256, "Enemy is too powerful!")