gdscript_basics.rst 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526
  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. It uses an indentation-based syntax similar to languages like
  9. `Python <https://en.wikipedia.org/wiki/Python_%28programming_language%29>`_.
  10. Its goal is to be optimized for and tightly integrated with Godot Engine,
  11. allowing great flexibility for content creation and integration.
  12. GDScript is entirely independent from Python and is not based on it.
  13. History
  14. -------
  15. .. note::
  16. Documentation about GDScript's history has been moved to the
  17. :ref:`Frequently Asked Questions <doc_faq_what_is_gdscript>`.
  18. Example of GDScript
  19. -------------------
  20. Some people can learn better by taking a look at the syntax, so
  21. here's an example of how GDScript looks.
  22. ::
  23. # Everything after "#" is a comment.
  24. # A file is a class!
  25. # (optional) icon to show in the editor dialogs:
  26. @icon("res://path/to/optional/icon.svg")
  27. # (optional) class definition:
  28. class_name MyClass
  29. # Inheritance:
  30. extends BaseClass
  31. # Member variables.
  32. var a = 5
  33. var s = "Hello"
  34. var arr = [1, 2, 3]
  35. var dict = {"key": "value", 2: 3}
  36. var other_dict = {key = "value", other_key = 2}
  37. var typed_var: int
  38. var inferred_type := "String"
  39. # Constants.
  40. const ANSWER = 42
  41. const THE_NAME = "Charly"
  42. # Enums.
  43. enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
  44. enum Named {THING_1, THING_2, ANOTHER_THING = -1}
  45. # Built-in vector types.
  46. var v2 = Vector2(1, 2)
  47. var v3 = Vector3(1, 2, 3)
  48. # Functions.
  49. func some_function(param1, param2, param3):
  50. const local_const = 5
  51. if param1 < local_const:
  52. print(param1)
  53. elif param2 > 5:
  54. print(param2)
  55. else:
  56. print("Fail!")
  57. for i in range(20):
  58. print(i)
  59. while param2 != 0:
  60. param2 -= 1
  61. match param3:
  62. 3:
  63. print("param3 is 3!")
  64. _:
  65. print("param3 is not 3!")
  66. var local_var = param1 + 3
  67. return local_var
  68. # Functions override functions with the same name on the base/super class.
  69. # If you still want to call them, use "super":
  70. func something(p1, p2):
  71. super(p1, p2)
  72. # It's also possible to call another function in the super class:
  73. func other_something(p1, p2):
  74. super.something(p1, p2)
  75. # Inner class
  76. class Something:
  77. var a = 10
  78. # Constructor
  79. func _init():
  80. print("Constructed!")
  81. var lv = Something.new()
  82. print(lv.a)
  83. If you have previous experience with statically typed languages such as
  84. C, C++, or C# but never used a dynamically typed one before, it is advised you
  85. read this tutorial: :ref:`doc_gdscript_more_efficiently`.
  86. Identifiers
  87. -----------
  88. Any string that restricts itself to alphabetic characters (``a`` to ``z`` and
  89. ``A`` to ``Z``), digits (``0`` to ``9``) and ``_`` qualifies as an identifier.
  90. Additionally, identifiers must not begin with a digit. Identifiers are
  91. case-sensitive (``foo`` is different from ``FOO``).
  92. Identifiers may also contain most Unicode characters part of
  93. `UAX#31 <https://www.unicode.org/reports/tr31/>`__. This allows you to use
  94. identifier names written in languages other than English. Unicode characters
  95. that are considered "confusable" for ASCII characters and emoji are not allowed
  96. in identifiers.
  97. Keywords
  98. --------
  99. The following is the list of keywords supported by the language. Since
  100. keywords are reserved words (tokens), they can't be used as identifiers.
  101. Operators (like ``in``, ``not``, ``and`` or ``or``) and names of built-in types
  102. as listed in the following sections are also reserved.
  103. Keywords are defined in the `GDScript tokenizer <https://github.com/godotengine/godot/blob/master/modules/gdscript/gdscript_tokenizer.cpp>`_
  104. in case you want to take a look under the hood.
  105. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  106. | Keyword | Description |
  107. +============+===================================================================================================================================================+
  108. | if | See `if/else/elif`_. |
  109. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  110. | elif | See `if/else/elif`_. |
  111. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  112. | else | See `if/else/elif`_. |
  113. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  114. | for | See for_. |
  115. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  116. | while | See while_. |
  117. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  118. | match | See match_. |
  119. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  120. | when | Used by `pattern guards <Pattern guards_>`_ in ``match`` statements. |
  121. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  122. | break | Exits the execution of the current ``for`` or ``while`` loop. |
  123. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  124. | continue | Immediately skips to the next iteration of the ``for`` or ``while`` loop. |
  125. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  126. | pass | Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions. |
  127. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  128. | return | Returns a value from a function. |
  129. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  130. | class | Defines an inner class. See `Inner classes`_. |
  131. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  132. | class_name | Defines the script as a globally accessible class with the specified name. See `Registering named classes`_. |
  133. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  134. | extends | Defines what class to extend with the current class. |
  135. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  136. | is | Tests whether a variable extends a given class, or is of a given built-in type. |
  137. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  138. | in | Tests whether a value is within a string, array, range, dictionary, or node. When used with ``for``, it iterates through them instead of testing. |
  139. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  140. | as | Cast the value to a given type if possible. |
  141. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  142. | self | Refers to current class instance. |
  143. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  144. | super | Resolves the scope of the parent method. See `Inheritance`_. |
  145. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  146. | signal | Defines a signal. |
  147. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  148. | func | Defines a function. |
  149. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  150. | static | Defines a static function or a static member variable. |
  151. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  152. | const | Defines a constant. |
  153. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  154. | enum | Defines an enum. |
  155. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  156. | var | Defines a variable. |
  157. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  158. | breakpoint | Editor helper for debugger breakpoints. Unlike breakpoints created by clicking in the gutter, ``breakpoint`` is stored in the script itself. |
  159. | | This makes it persistent across different machines when using version control. |
  160. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  161. | preload | Preloads a class or variable. See `Classes as resources`_. |
  162. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  163. | await | Waits for a signal or a coroutine to finish. See `Awaiting signals or coroutines`_. |
  164. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  165. | yield | Previously used for coroutines. Kept as keyword for transition. |
  166. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  167. | assert | Asserts a condition, logs error on failure. Ignored in non-debug builds. See `Assert keyword`_. |
  168. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  169. | void | Used to represent that a function does not return any value. |
  170. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  171. | PI | PI constant. |
  172. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  173. | TAU | TAU constant. |
  174. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  175. | INF | Infinity constant. Used for comparisons and as result of calculations. |
  176. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  177. | NAN | NAN (not a number) constant. Used as impossible result from calculations. |
  178. +------------+---------------------------------------------------------------------------------------------------------------------------------------------------+
  179. Operators
  180. ---------
  181. The following is the list of supported operators and their precedence. All binary operators are `left-associative <https://en.wikipedia.org/wiki/Operator_associativity>`_,
  182. including the ``**`` operator. This means that ``2 ** 2 ** 3`` is equal to ``(2 ** 2) ** 3``. Use parentheses to explicitly specify precedence you need, for
  183. example ``2 ** (2 ** 3)``. The ternary ``if/else`` operator is right-associative.
  184. +---------------------------------------+-----------------------------------------------------------------------------+
  185. | **Operator** | **Description** |
  186. +=======================================+=============================================================================+
  187. | ``(`` ``)`` | Grouping (highest priority) |
  188. | | |
  189. | | Parentheses are not really an operator, but allow you to explicitly specify |
  190. | | the precedence of an operation. |
  191. +---------------------------------------+-----------------------------------------------------------------------------+
  192. | ``x[index]`` | Subscription |
  193. +---------------------------------------+-----------------------------------------------------------------------------+
  194. | ``x.attribute`` | Attribute reference |
  195. +---------------------------------------+-----------------------------------------------------------------------------+
  196. | ``foo()`` | Function call |
  197. +---------------------------------------+-----------------------------------------------------------------------------+
  198. | ``await x`` | `Awaiting signals or coroutines`_ |
  199. +---------------------------------------+-----------------------------------------------------------------------------+
  200. | | ``x is Node`` | Type checking |
  201. | | ``x is not Node`` | |
  202. | | See also :ref:`is_instance_of() <class_@GDScript_method_is_instance_of>` |
  203. | | function. |
  204. +---------------------------------------+-----------------------------------------------------------------------------+
  205. | ``x ** y`` | Power |
  206. | | |
  207. | | Multiplies ``x`` by itself ``y`` times, similar to calling |
  208. | | :ref:`pow() <class_@GlobalScope_method_pow>` function. |
  209. +---------------------------------------+-----------------------------------------------------------------------------+
  210. | ``~x`` | Bitwise NOT |
  211. +---------------------------------------+-----------------------------------------------------------------------------+
  212. | | ``+x`` | Identity / Negation |
  213. | | ``-x`` | |
  214. +---------------------------------------+-----------------------------------------------------------------------------+
  215. | | ``x * y`` | Multiplication / Division / Remainder |
  216. | | ``x / y`` | |
  217. | | ``x % y`` | The ``%`` operator is additionally used for |
  218. | | :ref:`format strings <doc_gdscript_printf>`. |
  219. | | |
  220. | | **Note:** These operators have the same behavior as C++, which may be |
  221. | | unexpected for users coming from Python, JavaScript, etc. See a detailed |
  222. | | note after the table. |
  223. +---------------------------------------+-----------------------------------------------------------------------------+
  224. | | ``x + y`` | Addition (or Concatenation) / Subtraction |
  225. | | ``x - y`` | |
  226. +---------------------------------------+-----------------------------------------------------------------------------+
  227. | | ``x << y`` | Bit shifting |
  228. | | ``x >> y`` | |
  229. +---------------------------------------+-----------------------------------------------------------------------------+
  230. | ``x & y`` | Bitwise AND |
  231. +---------------------------------------+-----------------------------------------------------------------------------+
  232. | ``x ^ y`` | Bitwise XOR |
  233. +---------------------------------------+-----------------------------------------------------------------------------+
  234. | ``x | y`` | Bitwise OR |
  235. +---------------------------------------+-----------------------------------------------------------------------------+
  236. | | ``x == y`` | Comparison |
  237. | | ``x != y`` | |
  238. | | ``x < y`` | See a detailed note after the table. |
  239. | | ``x > y`` | |
  240. | | ``x <= y`` | |
  241. | | ``x >= y`` | |
  242. +---------------------------------------+-----------------------------------------------------------------------------+
  243. | | ``x in y`` | Inclusion checking |
  244. | | ``x not in y`` | |
  245. | | ``in`` is also used with the for_ keyword as part of the syntax. |
  246. +---------------------------------------+-----------------------------------------------------------------------------+
  247. | | ``not x`` | Boolean NOT and its :ref:`unrecommended <boolean_operators>` alias |
  248. | | ``!x`` | |
  249. +---------------------------------------+-----------------------------------------------------------------------------+
  250. | | ``x and y`` | Boolean AND and its :ref:`unrecommended <boolean_operators>` alias |
  251. | | ``x && y`` | |
  252. +---------------------------------------+-----------------------------------------------------------------------------+
  253. | | ``x or y`` | Boolean OR and its :ref:`unrecommended <boolean_operators>` alias |
  254. | | ``x || y`` | |
  255. +---------------------------------------+-----------------------------------------------------------------------------+
  256. | ``true_expr if cond else false_expr`` | Ternary if/else |
  257. +---------------------------------------+-----------------------------------------------------------------------------+
  258. | ``x as Node`` | `Type casting <casting_>`_ |
  259. +---------------------------------------+-----------------------------------------------------------------------------+
  260. | | ``x = y`` | Assignment (lowest priority) |
  261. | | ``x += y`` | |
  262. | | ``x -= y`` | You cannot use an assignment operator inside an expression. |
  263. | | ``x *= y`` | |
  264. | | ``x /= y`` | |
  265. | | ``x **= y`` | |
  266. | | ``x %= y`` | |
  267. | | ``x &= y`` | |
  268. | | ``x |= y`` | |
  269. | | ``x ^= y`` | |
  270. | | ``x <<= y`` | |
  271. | | ``x >>= y`` | |
  272. +---------------------------------------+-----------------------------------------------------------------------------+
  273. .. note::
  274. The behavior of some operators may differ from what you expect:
  275. 1. If both operands of the ``/`` operator are :ref:`int <class_int>`, then integer division is performed instead of fractional. For example ``5 / 2 == 2``, not ``2.5``.
  276. If this is not desired, use at least one :ref:`float <class_float>` literal (``x / 2.0``), cast (``float(x) / y``), or multiply by ``1.0`` (``x * 1.0 / y``).
  277. 2. The ``%`` operator is only available for ints, for floats use the :ref:`fmod() <class_@GlobalScope_method_fmod>` function.
  278. 3. For negative values, the ``%`` operator and ``fmod()`` use `truncation <https://en.wikipedia.org/wiki/Truncation>`_ instead of rounding towards negative infinity.
  279. This means that the remainder has a sign. If you need the remainder in a mathematical sense, use the :ref:`posmod() <class_@GlobalScope_method_posmod>` and
  280. :ref:`fposmod() <class_@GlobalScope_method_fposmod>` functions instead.
  281. 4. The ``==`` and ``!=`` operators sometimes allow you to compare values of different types (for example, ``1 == 1.0`` is true), but in other cases it can cause
  282. a runtime error. If you're not sure about the types of the operands, you can safely use the :ref:`is_same() <class_@GlobalScope_method_is_same>` function
  283. (but note that it is more strict about types and references). To compare floats, use the :ref:`is_equal_approx() <class_@GlobalScope_method_is_equal_approx>`
  284. and :ref:`is_zero_approx() <class_@GlobalScope_method_is_zero_approx>` functions instead.
  285. Literals
  286. --------
  287. +---------------------------------+-------------------------------------------+
  288. | **Example(s)** | **Description** |
  289. +---------------------------------+-------------------------------------------+
  290. | ``null`` | Null value |
  291. +---------------------------------+-------------------------------------------+
  292. | ``false``, ``true`` | Boolean values |
  293. +---------------------------------+-------------------------------------------+
  294. | ``45`` | Base 10 integer |
  295. +---------------------------------+-------------------------------------------+
  296. | ``0x8f51`` | Base 16 (hexadecimal) integer |
  297. +---------------------------------+-------------------------------------------+
  298. | ``0b101010`` | Base 2 (binary) integer |
  299. +---------------------------------+-------------------------------------------+
  300. | ``3.14``, ``58.1e-10`` | Floating-point number (real) |
  301. +---------------------------------+-------------------------------------------+
  302. | ``"Hello"``, ``'Hi'`` | Regular strings |
  303. +---------------------------------+-------------------------------------------+
  304. | ``"""Hello"""``, ``'''Hi'''`` | Triple-quoted regular strings |
  305. +---------------------------------+-------------------------------------------+
  306. | ``r"Hello"``, ``r'Hi'`` | Raw strings |
  307. +---------------------------------+-------------------------------------------+
  308. | ``r"""Hello"""``, ``r'''Hi'''`` | Triple-quoted raw strings |
  309. +---------------------------------+-------------------------------------------+
  310. | ``&"name"`` | :ref:`StringName <class_StringName>` |
  311. +---------------------------------+-------------------------------------------+
  312. | ``^"Node/Label"`` | :ref:`NodePath <class_NodePath>` |
  313. +---------------------------------+-------------------------------------------+
  314. There are also two constructs that look like literals, but actually are not:
  315. +---------------------------------+-------------------------------------------+
  316. | **Example** | **Description** |
  317. +---------------------------------+-------------------------------------------+
  318. | ``$NodePath`` | Shorthand for ``get_node("NodePath")`` |
  319. +---------------------------------+-------------------------------------------+
  320. | ``%UniqueNode`` | Shorthand for ``get_node("%UniqueNode")`` |
  321. +---------------------------------+-------------------------------------------+
  322. Integers and floats can have their numbers separated with ``_`` to make them more readable.
  323. The following ways to write numbers are all valid::
  324. 12_345_678 # Equal to 12345678.
  325. 3.141_592_7 # Equal to 3.1415927.
  326. 0x8080_0000_ffff # Equal to 0x80800000ffff.
  327. 0b11_00_11_00 # Equal to 0b11001100.
  328. **Regular string literals** can contain the following escape sequences:
  329. +---------------------+---------------------------------+
  330. | **Escape sequence** | **Expands to** |
  331. +---------------------+---------------------------------+
  332. | ``\n`` | Newline (line feed) |
  333. +---------------------+---------------------------------+
  334. | ``\t`` | Horizontal tab character |
  335. +---------------------+---------------------------------+
  336. | ``\r`` | Carriage return |
  337. +---------------------+---------------------------------+
  338. | ``\a`` | Alert (beep/bell) |
  339. +---------------------+---------------------------------+
  340. | ``\b`` | Backspace |
  341. +---------------------+---------------------------------+
  342. | ``\f`` | Formfeed page break |
  343. +---------------------+---------------------------------+
  344. | ``\v`` | Vertical tab character |
  345. +---------------------+---------------------------------+
  346. | ``\"`` | Double quote |
  347. +---------------------+---------------------------------+
  348. | ``\'`` | Single quote |
  349. +---------------------+---------------------------------+
  350. | ``\\`` | Backslash |
  351. +---------------------+---------------------------------+
  352. | ``\uXXXX`` | UTF-16 Unicode codepoint |
  353. | | ``XXXX`` |
  354. | | (hexadecimal, case-insensitive) |
  355. +---------------------+---------------------------------+
  356. | ``\UXXXXXX`` | UTF-32 Unicode codepoint |
  357. | | ``XXXXXX`` |
  358. | | (hexadecimal, case-insensitive) |
  359. +---------------------+---------------------------------+
  360. There are two ways to represent an escaped Unicode character above ``0xFFFF``:
  361. - as a `UTF-16 surrogate pair <https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF>`_ ``\uXXXX\uXXXX``.
  362. - as a single UTF-32 codepoint ``\UXXXXXX``.
  363. Also, using ``\`` followed by a newline inside a string will allow you to continue it in the next line,
  364. without inserting a newline character in the string itself.
  365. A string enclosed in quotes of one type (for example ``"``) can contain quotes of another type
  366. (for example ``'``) without escaping. Triple-quoted strings allow you to avoid escaping up to
  367. two consecutive quotes of the same type (unless they are adjacent to the string edges).
  368. **Raw string literals** always encode the string as it appears in the source code.
  369. This is especially useful for regular expressions. A raw string literal doesn't process escape sequences,
  370. however it does recognize ``\\`` and ``\"`` (``\'``) and replaces them with themselves.
  371. Thus, a string can have a quote that matches the opening one, but only if it's preceded by a backslash.
  372. ::
  373. print("\tchar=\"\\t\"") # Prints ` char="\t"`.
  374. print(r"\tchar=\"\\t\"") # Prints `\tchar=\"\\t\"`.
  375. .. note::
  376. Some strings cannot be represented using raw string literals: you cannot have an odd number
  377. of backslashes at the end of a string or have an unescaped opening quote inside the string.
  378. However, in practice this doesn't matter since you can use a different quote type
  379. or use concatenation with a regular string literal.
  380. GDScript also supports :ref:`format strings <doc_gdscript_printf>`.
  381. Annotations
  382. -----------
  383. Annotations are special tokens in GDScript that act as modifiers to a script or
  384. its code and may affect how the script is treated by the Godot engine or
  385. editor.
  386. Every annotation starts with the ``@`` character and is specified by a name. A
  387. detailed description and example for each annotation can be found inside the
  388. :ref:`GDScript class reference <class_@GDScript>`.
  389. For instance, you can use it to export a value to the editor::
  390. @export_range(1, 100, 1, "or_greater")
  391. var ranged_var: int = 50
  392. For more information about exporting properties, read the :ref:`GDScript exports <doc_gdscript_exports>`
  393. article.
  394. Any constant expression compatible with the required argument type can be passed as an annotation argument value::
  395. const MAX_SPEED = 120.0
  396. @export_range(0.0, 0.5 * MAX_SPEED)
  397. var initial_speed: float = 0.25 * MAX_SPEED
  398. Annotations can be specified one per line or all in the same line. They affect
  399. the next statement that isn't an annotation. Annotations can have arguments sent
  400. between parentheses and separated by commas.
  401. Both of these are the same::
  402. @annotation_a
  403. @annotation_b
  404. var variable
  405. @annotation_a @annotation_b var variable
  406. .. _doc_gdscript_onready_annotation:
  407. ``@onready`` annotation
  408. ~~~~~~~~~~~~~~~~~~~~~~~
  409. When using nodes, it's common to desire to keep references to parts
  410. of the scene in a variable. As scenes are only warranted to be
  411. configured when entering the active scene tree, the sub-nodes can only
  412. be obtained when a call to ``Node._ready()`` is made.
  413. ::
  414. var my_label
  415. func _ready():
  416. my_label = get_node("MyLabel")
  417. This can get a little cumbersome, especially when nodes and external
  418. references pile up. For this, GDScript has the ``@onready`` annotation, that
  419. defers initialization of a member variable until ``_ready()`` is called. It
  420. can replace the above code with a single line::
  421. @onready var my_label = get_node("MyLabel")
  422. .. warning::
  423. Applying ``@onready`` and any ``@export`` annotation to the same variable
  424. doesn't work as you might expect. The ``@onready`` annotation will cause
  425. the default value to be set after the ``@export`` takes effect and will
  426. override it::
  427. @export var a = "init_value_a"
  428. @onready @export var b = "init_value_b"
  429. func _init():
  430. prints(a, b) # init_value_a <null>
  431. func _notification(what):
  432. if what == NOTIFICATION_SCENE_INSTANTIATED:
  433. prints(a, b) # exported_value_a exported_value_b
  434. func _ready():
  435. prints(a, b) # exported_value_a init_value_b
  436. Therefore, the ``ONREADY_WITH_EXPORT`` warning is generated, which is treated
  437. as an error by default. We do not recommend disabling or ignoring it.
  438. Comments
  439. --------
  440. Anything from a ``#`` to the end of the line is ignored and is
  441. considered a comment.
  442. ::
  443. # This is a comment.
  444. .. tip::
  445. In the Godot script editor, special keywords are highlighted within comments
  446. to bring the user's attention to specific comments:
  447. - **Critical** *(appears in red)*: ``ALERT``, ``ATTENTION``, ``CAUTION``,
  448. ``CRITICAL``, ``DANGER``, ``SECURITY``
  449. - **Warning** *(appears in yellow)*: ``BUG``, ``DEPRECATED``, ``FIXME``,
  450. ``HACK``, ``TASK``, ``TBD``, ``TODO``, ``WARNING``
  451. - **Notice** *(appears in green)*: ``INFO``, ``NOTE``, ``NOTICE``, ``TEST``,
  452. ``TESTING``
  453. These keywords are case-sensitive, so they must be written in uppercase for them
  454. to be recognized:
  455. ::
  456. # In the example below, "TODO" will appear in yellow by default.
  457. # The `:` symbol after the keyword is not required, but it's often used.
  458. # TODO: Add more items for the player to choose from.
  459. The list of highlighted keywords and their colors can be changed in the **Text
  460. Editor > Theme > Comment Markers** section of the Editor Settings.
  461. Use two hash symbols (``##``) instead of one (``#``) to add a *documentation
  462. comment*, which will appear in the script documentation and in the inspector
  463. description of an exported variable. Documentation comments must be placed
  464. directly *above* a documentable item (such as a member variable), or at the top
  465. of a file. Dedicated formatting options are also available. See
  466. :ref:`doc_gdscript_documentation_comments` for details.
  467. ::
  468. ## This comment will appear in the script documentation.
  469. var value
  470. ## This comment will appear in the inspector tooltip, and in the documentation.
  471. @export var exported_value
  472. Code regions
  473. ------------
  474. Code regions are special types of comments that the script editor understands as
  475. *foldable regions*. This means that after writing code region comments, you can
  476. collapse and expand the region by clicking the arrow that appears at the left of
  477. the comment. This arrow appears within a purple square to be distinguishable
  478. from standard code folding.
  479. The syntax is as follows:
  480. ::
  481. # Important: There must be *no* space between the `#` and `region` or `endregion`.
  482. # Region without a description:
  483. #region
  484. ...
  485. #endregion
  486. # Region with a description:
  487. #region Some description that is displayed even when collapsed
  488. ...
  489. #endregion
  490. .. tip::
  491. To create a code region quickly, select several lines in the script editor,
  492. right-click the selection then choose **Create Code Region**. The region
  493. description will be selected automatically for editing.
  494. It is possible to nest code regions within other code regions.
  495. Here's a concrete usage example of code regions:
  496. ::
  497. # This comment is outside the code region. It will be visible when collapsed.
  498. #region Terrain generation
  499. # This comment is inside the code region. It won't be visible when collapsed.
  500. func generate_lakes():
  501. pass
  502. func generate_hills():
  503. pass
  504. #endregion
  505. #region Terrain population
  506. func place_vegetation():
  507. pass
  508. func place_roads():
  509. pass
  510. #endregion
  511. This can be useful to organize large chunks of code into easier to understand
  512. sections. However, remember that external editors generally don't support this
  513. feature, so make sure your code is easy to follow even when not relying on
  514. folding code regions.
  515. .. note::
  516. Individual functions and indented sections (such as ``if`` and ``for``) can
  517. *always* be collapsed in the script editor. This means you should avoid
  518. using a code region to contain a single function or indented section, as it
  519. won't bring much of a benefit. Code regions work best when they're used to
  520. group multiple elements together.
  521. Line continuation
  522. -----------------
  523. A line of code in GDScript can be continued on the next line by using a backslash
  524. (``\``). Add one at the end of a line and the code on the next line will act like
  525. it's where the backslash is. Here is an example:
  526. ::
  527. var a = 1 + \
  528. 2
  529. A line can be continued multiple times like this:
  530. ::
  531. var a = 1 + \
  532. 4 + \
  533. 10 + \
  534. 4
  535. .. _doc_gdscript_builtin_types:
  536. Built-in types
  537. --------------
  538. Built-in types are stack-allocated. They are passed as values. This means a copy
  539. is created on each assignment or when passing them as arguments to functions.
  540. The exceptions are ``Object``, ``Array``, ``Dictionary``, and packed arrays
  541. (such as ``PackedByteArray``), which are passed by reference so they are shared.
  542. All arrays, ``Dictionary``, and some objects (``Node``, ``Resource``)
  543. have a ``duplicate()`` method that allows you to make a copy.
  544. Basic built-in types
  545. ~~~~~~~~~~~~~~~~~~~~
  546. A variable in GDScript can be assigned to several built-in types.
  547. null
  548. ^^^^
  549. ``null`` is an empty data type that contains no information and can not
  550. be assigned any other value.
  551. Only types that inherit from Object can have a ``null`` value
  552. (Object is therefore called a "nullable" type).
  553. :ref:`Variant types <doc_variant_class>` must have a valid value at all times,
  554. and therefore cannot have a ``null`` value.
  555. :ref:`bool <class_bool>`
  556. ^^^^^^^^^^^^^^^^^^^^^^^^
  557. Short for "boolean", it can only contain ``true`` or ``false``.
  558. :ref:`int <class_int>`
  559. ^^^^^^^^^^^^^^^^^^^^^^
  560. Short for "integer", it stores whole numbers (positive and negative).
  561. It is stored as a 64-bit value, equivalent to ``int64_t`` in C++.
  562. :ref:`float <class_float>`
  563. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  564. Stores real numbers, including decimals, using floating-point values.
  565. It is stored as a 64-bit value, equivalent to ``double`` in C++.
  566. Note: Currently, data structures such as ``Vector2``, ``Vector3``, and
  567. ``PackedFloat32Array`` store 32-bit single-precision ``float`` values.
  568. :ref:`String <class_String>`
  569. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  570. A sequence of characters in `Unicode format <https://en.wikipedia.org/wiki/Unicode>`_.
  571. :ref:`StringName <class_StringName>`
  572. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  573. An immutable string that allows only one instance of each name. They are slower to
  574. create and may result in waiting for locks when multithreading. In exchange, they're
  575. very fast to compare, which makes them good candidates for dictionary keys.
  576. :ref:`NodePath <class_NodePath>`
  577. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  578. A pre-parsed path to a node or a node property. It can be
  579. easily assigned to, and from, a String. They are useful to interact with
  580. the tree to get a node, or affecting properties like with :ref:`Tweens <class_Tween>`.
  581. Vector built-in types
  582. ~~~~~~~~~~~~~~~~~~~~~
  583. :ref:`Vector2 <class_Vector2>`
  584. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  585. 2D vector type containing ``x`` and ``y`` fields. Can also be
  586. accessed as an array.
  587. :ref:`Vector2i <class_Vector2i>`
  588. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  589. Same as a Vector2 but the components are integers. Useful for representing
  590. items in a 2D grid.
  591. :ref:`Rect2 <class_Rect2>`
  592. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  593. 2D Rectangle type containing two vectors fields: ``position`` and ``size``.
  594. Also contains an ``end`` field which is ``position + size``.
  595. :ref:`Vector3 <class_Vector3>`
  596. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  597. 3D vector type containing ``x``, ``y`` and ``z`` fields. This can also
  598. be accessed as an array.
  599. :ref:`Vector3i <class_Vector3i>`
  600. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  601. Same as Vector3 but the components are integers. Can be use for indexing items
  602. in a 3D grid.
  603. :ref:`Transform2D <class_Transform2D>`
  604. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  605. 3×2 matrix used for 2D transforms.
  606. :ref:`Plane <class_Plane>`
  607. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  608. 3D Plane type in normalized form that contains a ``normal`` vector field
  609. and a ``d`` scalar distance.
  610. :ref:`Quaternion <class_Quaternion>`
  611. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  612. Quaternion is a datatype used for representing a 3D rotation. It's
  613. useful for interpolating rotations.
  614. :ref:`AABB <class_AABB>`
  615. ^^^^^^^^^^^^^^^^^^^^^^^^
  616. Axis-aligned bounding box (or 3D box) contains 2 vectors fields: ``position``
  617. and ``size``. Also contains an ``end`` field which is
  618. ``position + size``.
  619. :ref:`Basis <class_Basis>`
  620. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  621. 3x3 matrix used for 3D rotation and scale. It contains 3 vector fields
  622. (``x``, ``y`` and ``z``) and can also be accessed as an array of 3D
  623. vectors.
  624. :ref:`Transform3D <class_Transform3D>`
  625. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  626. 3D Transform contains a Basis field ``basis`` and a Vector3 field
  627. ``origin``.
  628. Engine built-in types
  629. ~~~~~~~~~~~~~~~~~~~~~
  630. :ref:`Color <class_Color>`
  631. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  632. Color data type contains ``r``, ``g``, ``b``, and ``a`` fields. It can
  633. also be accessed as ``h``, ``s``, and ``v`` for hue/saturation/value.
  634. :ref:`RID <class_RID>`
  635. ^^^^^^^^^^^^^^^^^^^^^^
  636. Resource ID (RID). Servers use generic RIDs to reference opaque data.
  637. :ref:`Object <class_Object>`
  638. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  639. Base class for anything that is not a built-in type.
  640. Container built-in types
  641. ~~~~~~~~~~~~~~~~~~~~~~~~
  642. :ref:`Array <class_Array>`
  643. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  644. Generic sequence of arbitrary object types, including other arrays or dictionaries (see below).
  645. The array can resize dynamically. Arrays are indexed starting from index ``0``.
  646. Negative indices count from the end.
  647. ::
  648. var arr = []
  649. arr = [1, 2, 3]
  650. var b = arr[1] # This is 2.
  651. var c = arr[arr.size() - 1] # This is 3.
  652. var d = arr[-1] # Same as the previous line, but shorter.
  653. arr[0] = "Hi!" # Replacing value 1 with "Hi!".
  654. arr.append(4) # Array is now ["Hi!", 2, 3, 4].
  655. Typed arrays
  656. ^^^^^^^^^^^^
  657. Godot 4.0 added support for typed arrays. On write operations, Godot checks that
  658. element values match the specified type, so the array cannot contain invalid values.
  659. The GDScript static analyzer takes typed arrays into account, however array methods like
  660. ``front()`` and ``back()`` still have the ``Variant`` return type.
  661. Typed arrays have the syntax ``Array[Type]``, where ``Type`` can be any ``Variant`` type,
  662. native or user class, or enum. Nested array types (like ``Array[Array[int]]``) are not supported.
  663. ::
  664. var a: Array[int]
  665. var b: Array[Node]
  666. var c: Array[MyClass]
  667. var d: Array[MyEnum]
  668. var e: Array[Variant]
  669. ``Array`` and ``Array[Variant]`` are the same thing.
  670. .. note::
  671. Arrays are passed by reference, so the array element type is also an attribute of the in-memory
  672. structure referenced by a variable in runtime. The static type of a variable restricts the structures
  673. that it can reference to. Therefore, you **cannot** assign an array with a different element type,
  674. even if the type is a subtype of the required type.
  675. If you want to *convert* a typed array, you can create a new array and use the
  676. :ref:`Array.assign() <class_Array_method_assign>` method::
  677. var a: Array[Node2D] = [Node2D.new()]
  678. # (OK) You can add the value to the array because `Node2D` extends `Node`.
  679. var b: Array[Node] = [a[0]]
  680. # (Error) You cannot assign an `Array[Node2D]` to an `Array[Node]` variable.
  681. b = a
  682. # (OK) But you can use the `assign()` method instead. Unlike the `=` operator,
  683. # the `assign()` method copies the contents of the array, not the reference.
  684. b.assign(a)
  685. The only exception was made for the ``Array`` (``Array[Variant]``) type, for user convenience
  686. and compatibility with old code. However, operations on untyped arrays are considered unsafe.
  687. Packed arrays
  688. ^^^^^^^^^^^^^
  689. PackedArrays are generally faster to iterate on and modify compared to a typed
  690. Array of the same type (e.g. PackedInt64Array versus Array[int]) and consume
  691. less memory. In the worst case, they are expected to be as fast as an untyped
  692. Array. Conversely, non-Packed Arrays (typed or not) have extra convenience
  693. methods such as :ref:`Array.map <class_Array_method_map>` that PackedArrays
  694. lack. Consult the :ref:`class reference <class_PackedFloat32Array>` for details
  695. on the methods available. Typed Arrays are generally faster to iterate on and
  696. modify than untyped Arrays.
  697. While all Arrays can cause memory fragmentation when they become large enough,
  698. if memory usage and performance (iteration and modification speed) is a concern
  699. and the type of data you're storing is compatible with one of the ``Packed``
  700. Array types, then using those may yield improvements. However, if you do not
  701. have such concerns (e.g. the size of your array does not reach the tens of
  702. thousands of elements) it is likely more helpful to use regular or typed
  703. Arrays, as they provide convenience methods that can make your code easier to
  704. write and maintain (and potentially faster if your data requires such
  705. operations a lot). If the data you will store is of a known type (including
  706. your own defined classes), prefer to use a typed Array as it may yield better
  707. performance in iteration and modification compared to an untyped Array.
  708. - :ref:`PackedByteArray <class_PackedByteArray>`: An array of bytes (integers from 0 to 255).
  709. - :ref:`PackedInt32Array <class_PackedInt32Array>`: An array of 32-bit integers.
  710. - :ref:`PackedInt64Array <class_PackedInt64Array>`: An array of 64-bit integers.
  711. - :ref:`PackedFloat32Array <class_PackedFloat32Array>`: An array of 32-bit floats.
  712. - :ref:`PackedFloat64Array <class_PackedFloat64Array>`: An array of 64-bit floats.
  713. - :ref:`PackedStringArray <class_PackedStringArray>`: An array of strings.
  714. - :ref:`PackedVector2Array <class_PackedVector2Array>`: An array of :ref:`Vector2 <class_Vector2>` values.
  715. - :ref:`PackedVector3Array <class_PackedVector3Array>`: An array of :ref:`Vector3 <class_Vector3>` values.
  716. - :ref:`PackedVector4Array <class_PackedVector4Array>`: An array of :ref:`Vector4 <class_Vector4>` values.
  717. - :ref:`PackedColorArray <class_PackedColorArray>`: An array of :ref:`Color <class_Color>` values.
  718. :ref:`Dictionary <class_Dictionary>`
  719. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  720. Associative container which contains values referenced by unique keys.
  721. ::
  722. var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
  723. d["Hi!"] = 0
  724. d = {
  725. 22: "value",
  726. "some_key": 2,
  727. "other_key": [2, 3, 4],
  728. "more_key": "Hello"
  729. }
  730. Lua-style table syntax is also supported. Lua-style uses ``=`` instead of ``:``
  731. and doesn't use quotes to mark string keys (making for slightly less to write).
  732. However, keys written in this form can't start with a digit (like any GDScript
  733. identifier), and must be string literals.
  734. ::
  735. var d = {
  736. test22 = "value",
  737. some_key = 2,
  738. other_key = [2, 3, 4],
  739. more_key = "Hello"
  740. }
  741. To add a key to an existing dictionary, access it like an existing key and
  742. assign to it::
  743. var d = {} # Create an empty Dictionary.
  744. d.waiting = 14 # Add String "waiting" as a key and assign the value 14 to it.
  745. d[4] = "hello" # Add integer 4 as a key and assign the String "hello" as its value.
  746. d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it.
  747. var test = 4
  748. # Prints "hello" by indexing the dictionary with a dynamic key.
  749. # This is not the same as `d.test`. The bracket syntax equivalent to
  750. # `d.test` is `d["test"]`.
  751. print(d[test])
  752. .. note::
  753. The bracket syntax can be used to access properties of any
  754. :ref:`class_Object`, not just Dictionaries. Keep in mind it will cause a
  755. script error when attempting to index a non-existing property. To avoid
  756. this, use the :ref:`Object.get() <class_Object_method_get>` and
  757. :ref:`Object.set() <class_Object_method_set>` methods instead.
  758. :ref:`Signal <class_Signal>`
  759. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  760. A signal is a message that can be emitted by an object to those who want to
  761. listen to it. The Signal type can be used for passing the emitter around.
  762. Signals are better used by getting them from actual objects, e.g. ``$Button.button_up``.
  763. :ref:`Callable <class_Callable>`
  764. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  765. Contains an object and a function, which is useful for passing functions as
  766. values (e.g. when connecting to signals).
  767. Getting a method as a member returns a callable. ``var x = $Sprite2D.rotate``
  768. will set the value of ``x`` to a callable with ``$Sprite2D`` as the object and
  769. ``rotate`` as the method.
  770. You can call it using the ``call`` method: ``x.call(PI)``.
  771. Variables
  772. ---------
  773. Variables can exist as class members or local to functions. They are
  774. created with the ``var`` keyword and may, optionally, be assigned a
  775. value upon initialization.
  776. ::
  777. var a # Data type is 'null' by default.
  778. var b = 5
  779. var c = 3.8
  780. var d = b + c # Variables are always initialized in direct order (see below).
  781. Variables can optionally have a type specification. When a type is specified,
  782. the variable will be forced to have always that same type, and trying to assign
  783. an incompatible value will raise an error.
  784. Types are specified in the variable declaration using a ``:`` (colon) symbol
  785. after the variable name, followed by the type.
  786. ::
  787. var my_vector2: Vector2
  788. var my_node: Node = Sprite2D.new()
  789. If the variable is initialized within the declaration, the type can be inferred, so
  790. it's possible to omit the type name::
  791. var my_vector2 := Vector2() # 'my_vector2' is of type 'Vector2'.
  792. var my_node := Sprite2D.new() # 'my_node' is of type 'Sprite2D'.
  793. Type inference is only possible if the assigned value has a defined type, otherwise
  794. it will raise an error.
  795. Valid types are:
  796. - Built-in types (Array, Vector2, int, String, etc.).
  797. - Engine classes (Node, Resource, RefCounted, etc.).
  798. - Constant names if they contain a script resource (``MyScript`` if you declared ``const MyScript = preload("res://my_script.gd")``).
  799. - Other classes in the same script, respecting scope (``InnerClass.NestedClass`` if you declared ``class NestedClass`` inside the ``class InnerClass`` in the same scope).
  800. - Script classes declared with the ``class_name`` keyword.
  801. - Autoloads registered as singletons.
  802. .. note::
  803. While ``Variant`` is a valid type specification, it's not an actual type. It
  804. only means there's no set type and is equivalent to not having a static type
  805. at all. Therefore, inference is not allowed by default for ``Variant``,
  806. since it's likely a mistake.
  807. You can turn off this check, or make it only a warning, by changing it in
  808. the project settings. See :ref:`doc_gdscript_warning_system` for details.
  809. Initialization order
  810. ~~~~~~~~~~~~~~~~~~~~
  811. Member variables are initialized in the following order:
  812. 1. Depending on the variable's static type, the variable is either ``null``
  813. (untyped variables and objects) or has a default value of the type
  814. (``0`` for ``int``, ``false`` for ``bool``, etc.).
  815. 2. The specified values are assigned in the order of the variables in the script,
  816. from top to bottom.
  817. - (Only for ``Node``-derived classes) If the ``@onready`` annotation is applied to a variable,
  818. its initialization is deferred to step 5.
  819. 3. If defined, the ``_init()`` method is called.
  820. 4. When instantiating scenes and resources, the exported values are assigned.
  821. 5. (Only for ``Node``-derived classes) ``@onready`` variables are initialized.
  822. 6. (Only for ``Node``-derived classes) If defined, the ``_ready()`` method is called.
  823. .. warning::
  824. You can specify a complex expression as a variable initializer, including function calls.
  825. Make sure the variables are initialized in the correct order, otherwise your values
  826. may be overwritten. For example::
  827. var a: int = proxy("a", 1)
  828. var b: int = proxy("b", 2)
  829. var _data: Dictionary = {}
  830. func proxy(key: String, value: int):
  831. _data[key] = value
  832. print(_data)
  833. return value
  834. func _init() -> void:
  835. print(_data)
  836. Will print::
  837. { "a": 1 }
  838. { "a": 1, "b": 2 }
  839. { }
  840. To fix this, move the ``_data`` variable definition above the ``a`` definition
  841. or remove the empty dictionary assignment (``= {}``).
  842. Static variables
  843. ~~~~~~~~~~~~~~~~
  844. A class member variable can be declared static::
  845. static var a
  846. Static variables belong to the class, not instances. This means that static variables
  847. share values between multiple instances, unlike regular member variables.
  848. From inside a class, you can access static variables from any function, both static and non-static.
  849. From outside the class, you can access static variables using the class or an instance
  850. (the second is not recommended as it is less readable).
  851. .. note::
  852. The ``@export`` and ``@onready`` annotations cannot be applied to a static variable.
  853. Local variables cannot be static.
  854. The following example defines a ``Person`` class with a static variable named ``max_id``.
  855. We increment the ``max_id`` in the ``_init()`` function. This makes it easy to keep track
  856. of the number of ``Person`` instances in our game.
  857. ::
  858. # person.gd
  859. class_name Person
  860. static var max_id = 0
  861. var id
  862. var name
  863. func _init(p_name):
  864. max_id += 1
  865. id = max_id
  866. name = p_name
  867. In this code, we create two instances of our ``Person`` class and check that the class
  868. and every instance have the same ``max_id`` value, because the variable is static and accessible to every instance.
  869. ::
  870. # test.gd
  871. extends Node
  872. func _ready():
  873. var person1 = Person.new("John Doe")
  874. var person2 = Person.new("Jane Doe")
  875. print(person1.id) # 1
  876. print(person2.id) # 2
  877. print(Person.max_id) # 2
  878. print(person1.max_id) # 2
  879. print(person2.max_id) # 2
  880. Static variables can have type hints, setters and getters::
  881. static var balance: int = 0
  882. static var debt: int:
  883. get:
  884. return -balance
  885. set(value):
  886. balance = -value
  887. A base class static variable can also be accessed via a child class::
  888. class A:
  889. static var x = 1
  890. class B extends A:
  891. pass
  892. func _ready():
  893. prints(A.x, B.x) # 1 1
  894. A.x = 2
  895. prints(A.x, B.x) # 2 2
  896. B.x = 3
  897. prints(A.x, B.x) # 3 3
  898. ``@static_unload`` annotation
  899. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  900. Since GDScript classes are resources, having static variables in a script prevents it from being unloaded
  901. even if there are no more instances of that class and no other references left. This can be important
  902. if static variables store large amounts of data or hold references to other project resources, such as scenes.
  903. You should clean up this data manually, or use the :ref:`@static_unload <class_@GDScript_annotation_@static_unload>`
  904. annotation if static variables don't store important data and can be reset.
  905. .. warning::
  906. Currently, due to a bug, scripts are never freed, even if ``@static_unload`` annotation is used.
  907. Note that ``@static_unload`` applies to the entire script (including inner classes)
  908. and must be placed at the top of the script, before ``class_name`` and ``extends``::
  909. @static_unload
  910. class_name MyNode
  911. extends Node
  912. See also `Static functions`_ and `Static constructor`_.
  913. Casting
  914. ~~~~~~~
  915. Values assigned to typed variables must have a compatible type. If it's needed to
  916. coerce a value to be of a certain type, in particular for object types, you can
  917. use the casting operator ``as``.
  918. Casting between object types results in the same object if the value is of the
  919. same type or a subtype of the cast type.
  920. ::
  921. var my_node2D: Node2D
  922. my_node2D = $Sprite2D as Node2D # Works since Sprite2D is a subtype of Node2D.
  923. If the value is not a subtype, the casting operation will result in a ``null`` value.
  924. ::
  925. var my_node2D: Node2D
  926. my_node2D = $Button as Node2D # Results in 'null' since a Button is not a subtype of Node2D.
  927. For built-in types, they will be forcibly converted if possible, otherwise the
  928. engine will raise an error.
  929. ::
  930. var my_int: int
  931. my_int = "123" as int # The string can be converted to int.
  932. my_int = Vector2() as int # A Vector2 can't be converted to int, this will cause an error.
  933. Casting is also useful to have better type-safe variables when interacting with
  934. the scene tree::
  935. # Will infer the variable to be of type Sprite2D.
  936. var my_sprite := $Character as Sprite2D
  937. # Will fail if $AnimPlayer is not an AnimationPlayer, even if it has the method 'play()'.
  938. ($AnimPlayer as AnimationPlayer).play("walk")
  939. Constants
  940. ---------
  941. Constants are values you cannot change when the game is running.
  942. Their value must be known at compile-time. Using the
  943. ``const`` keyword allows you to give a constant value a name. Trying to assign a
  944. value to a constant after it's declared will give you an error.
  945. We recommend using constants whenever a value is not meant to change.
  946. ::
  947. const A = 5
  948. const B = Vector2(20, 20)
  949. const C = 10 + 20 # Constant expression.
  950. const D = Vector2(20, 30).x # Constant expression: 20.
  951. const E = [1, 2, 3, 4][0] # Constant expression: 1.
  952. const F = sin(20) # 'sin()' can be used in constant expressions.
  953. const G = x + 20 # Invalid; this is not a constant expression!
  954. const H = A + 20 # Constant expression: 25 (`A` is a constant).
  955. Although the type of constants is inferred from the assigned value, it's also
  956. possible to add explicit type specification::
  957. const A: int = 5
  958. const B: Vector2 = Vector2()
  959. Assigning a value of an incompatible type will raise an error.
  960. You can also create constants inside a function, which is useful to name local
  961. magic values.
  962. Enums
  963. ~~~~~
  964. Enums are basically a shorthand for constants, and are pretty useful if you
  965. want to assign consecutive integers to some constant.
  966. ::
  967. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  968. # Is the same as:
  969. const TILE_BRICK = 0
  970. const TILE_FLOOR = 1
  971. const TILE_SPIKE = 2
  972. const TILE_TELEPORT = 3
  973. If you pass a name to the enum, it will put all the keys inside a constant
  974. :ref:`Dictionary <class_Dictionary>` of that name. This means all constant methods of
  975. a dictionary can also be used with a named enum.
  976. .. important:: Keys in a named enum are not registered
  977. as global constants. They should be accessed prefixed
  978. by the enum's name (``Name.KEY``).
  979. ::
  980. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  981. # Is the same as:
  982. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  983. # Access values with State.STATE_IDLE, etc.
  984. func _ready():
  985. # Access values with Name.KEY, prints '5'
  986. print(State.STATE_JUMP)
  987. # Use dictionary methods:
  988. # prints '["STATE_IDLE", "STATE_JUMP", "STATE_SHOOT"]'
  989. print(State.keys())
  990. # prints '{ "STATE_IDLE": 0, "STATE_JUMP": 5, "STATE_SHOOT": 6 }'
  991. print(State)
  992. # prints '[0, 5, 6]'
  993. print(State.values())
  994. If not assigning a value to a key of an enum it will be assigned the previous value plus one,
  995. or ``0`` if it is the first entry in the enum. Multiple keys with the same value are allowed.
  996. Functions
  997. ---------
  998. Functions always belong to a `class <Classes_>`_. The scope priority for
  999. variable look-up is: local → class member → global. The ``self`` variable is
  1000. always available and is provided as an option for accessing class members, but
  1001. is not always required (and should *not* be sent as the function's first
  1002. argument, unlike Python).
  1003. ::
  1004. func my_function(a, b):
  1005. print(a)
  1006. print(b)
  1007. return a + b # Return is optional; without it 'null' is returned.
  1008. A function can ``return`` at any point. The default return value is ``null``.
  1009. If a function contains only one line of code, it can be written on one line::
  1010. func square(a): return a * a
  1011. func hello_world(): print("Hello World")
  1012. func empty_function(): pass
  1013. Functions can also have type specification for the arguments and for the return
  1014. value. Types for arguments can be added in a similar way to variables::
  1015. func my_function(a: int, b: String):
  1016. pass
  1017. If a function argument has a default value, it's possible to infer the type::
  1018. func my_function(int_arg := 42, String_arg := "string"):
  1019. pass
  1020. The return type of the function can be specified after the arguments list using
  1021. the arrow token (``->``)::
  1022. func my_int_function() -> int:
  1023. return 0
  1024. Functions that have a return type **must** return a proper value. Setting the
  1025. type as ``void`` means the function doesn't return anything. Void functions can
  1026. return early with the ``return`` keyword, but they can't return any value.
  1027. ::
  1028. func void_function() -> void:
  1029. return # Can't return a value.
  1030. .. note:: Non-void functions must **always** return a value, so if your code has
  1031. branching statements (such as an ``if``/``else`` construct), all the
  1032. possible paths must have a return. E.g., if you have a ``return``
  1033. inside an ``if`` block but not after it, the editor will raise an
  1034. error because if the block is not executed, the function won't have a
  1035. valid value to return.
  1036. Referencing functions
  1037. ~~~~~~~~~~~~~~~~~~~~~
  1038. Functions are first-class values in terms of the :ref:`Callable <class_Callable>` object.
  1039. Referencing a function by name without calling it will automatically generate the proper
  1040. callable. This can be used to pass functions as arguments.
  1041. ::
  1042. func map(arr: Array, function: Callable) -> Array:
  1043. var result = []
  1044. for item in arr:
  1045. result.push_back(function.call(item))
  1046. return result
  1047. func add1(value: int) -> int:
  1048. return value + 1;
  1049. func _ready() -> void:
  1050. var my_array = [1, 2, 3]
  1051. var plus_one = map(my_array, add1)
  1052. print(plus_one) # Prints `[2, 3, 4]`.
  1053. .. note::
  1054. Callables **must** be called with the :ref:`call() <class_Callable_method_call>` method.
  1055. You cannot use the ``()`` operator directly. This behavior is implemented to avoid
  1056. performance issues on direct function calls.
  1057. Lambda functions
  1058. ~~~~~~~~~~~~~~~~
  1059. Lambda functions allow you to declare functions that do not belong to a class. Instead, a
  1060. :ref:`Callable <class_Callable>` object is created and assigned to a variable directly.
  1061. This can be useful to create callables to pass around without polluting the class scope.
  1062. ::
  1063. var lambda = func (x):
  1064. print(x)
  1065. To call the created lambda you can use the :ref:`call() <class_Callable_method_call>` method::
  1066. lambda.call(42) # Prints `42`.
  1067. Lambda functions can be named for debugging purposes (the name is displayed in the Debugger)::
  1068. var lambda = func my_lambda(x):
  1069. print(x)
  1070. You can specify type hints for lambda functions in the same way as for regular ones::
  1071. var lambda := func (x: int) -> void:
  1072. print(x)
  1073. Note that if you want to return a value from a lambda function, an explicit ``return``
  1074. is required (you can't omit ``return``)::
  1075. var lambda = func (x): return x ** 2
  1076. print(lambda.call(2)) # Prints `4`.
  1077. Lambda functions capture the local environment::
  1078. var x = 42
  1079. var lambda = func ():
  1080. print(x) # Prints `42`.
  1081. lambda.call()
  1082. .. warning::
  1083. Local variables are captured by value once, when the lambda is created.
  1084. So they won't be updated in the lambda if reassigned in the outer function::
  1085. var x = 42
  1086. var lambda = func (): print(x)
  1087. lambda.call() # Prints `42`.
  1088. x = "Hello"
  1089. lambda.call() # Prints `42`.
  1090. Also, a lambda cannot reassign an outer local variable. After exiting the lambda,
  1091. the variable will be unchanged, because the lambda capture implicitly shadows it::
  1092. var x = 42
  1093. var lambda = func ():
  1094. print(x) # Prints `42`.
  1095. x = "Hello" # Produces the `CONFUSABLE_CAPTURE_REASSIGNMENT` warning.
  1096. print(x) # Prints `Hello`.
  1097. lambda.call()
  1098. print(x) # Prints `42`.
  1099. However, if you use pass-by-reference data types (arrays, dictionaries, and objects),
  1100. then the content changes are shared until you reassign the variable::
  1101. var a = []
  1102. var lambda = func ():
  1103. a.append(1)
  1104. print(a) # Prints `[1]`.
  1105. a = [2] # Produces the `CONFUSABLE_CAPTURE_REASSIGNMENT` warning.
  1106. print(a) # Prints `[2]`.
  1107. lambda.call()
  1108. print(a) # Prints `[1]`.
  1109. Static functions
  1110. ~~~~~~~~~~~~~~~~
  1111. A function can be declared static. When a function is static, it has no access to the instance member variables or ``self``.
  1112. A static function has access to static variables. Also static functions are useful to make libraries of helper functions::
  1113. static func sum2(a, b):
  1114. return a + b
  1115. Lambda functions cannot be declared static.
  1116. See also `Static variables`_ and `Static constructor`_.
  1117. Statements and control flow
  1118. ---------------------------
  1119. Statements are standard and can be assignments, function calls, control
  1120. flow structures, etc (see below). ``;`` as a statement separator is
  1121. entirely optional.
  1122. Expressions
  1123. ~~~~~~~~~~~
  1124. Expressions are sequences of operators and their operands in orderly fashion. An expression by itself can be a
  1125. statement too, though only calls are reasonable to use as statements since other expressions don't have side effects.
  1126. Expressions return values that can be assigned to valid targets. Operands to some operator can be another
  1127. expression. An assignment is not an expression and thus does not return any value.
  1128. Here are some examples of expressions::
  1129. 2 + 2 # Binary operation.
  1130. -5 # Unary operation.
  1131. "okay" if x > 4 else "not okay" # Ternary operation.
  1132. x # Identifier representing variable or constant.
  1133. x.a # Attribute access.
  1134. x[4] # Subscript access.
  1135. x > 2 or x < 5 # Comparisons and logic operators.
  1136. x == y + 2 # Equality test.
  1137. do_something() # Function call.
  1138. [1, 2, 3] # Array definition.
  1139. {A = 1, B = 2} # Dictionary definition.
  1140. preload("res://icon.png") # Preload builtin function.
  1141. self # Reference to current instance.
  1142. Identifiers, attributes, and subscripts are valid assignment targets. Other expressions cannot be on the left side of
  1143. an assignment.
  1144. if/else/elif
  1145. ~~~~~~~~~~~~
  1146. Simple conditions are created by using the ``if``/``else``/``elif`` syntax.
  1147. Parenthesis around conditions are allowed, but not required. Given the
  1148. nature of the tab-based indentation, ``elif`` can be used instead of
  1149. ``else``/``if`` to maintain a level of indentation.
  1150. ::
  1151. if (expression):
  1152. statement(s)
  1153. elif (expression):
  1154. statement(s)
  1155. else:
  1156. statement(s)
  1157. Short statements can be written on the same line as the condition::
  1158. if 1 + 1 == 2: return 2 + 2
  1159. else:
  1160. var x = 3 + 3
  1161. return x
  1162. Sometimes, you might want to assign a different initial value based on a
  1163. boolean expression. In this case, ternary-if expressions come in handy::
  1164. var x = (value) if (expression) else (value)
  1165. y += 3 if y < 10 else -1
  1166. Ternary-if expressions can be nested to handle more than 2 cases. When nesting
  1167. ternary-if expressions, it is recommended to wrap the complete expression over
  1168. multiple lines to preserve readability::
  1169. var count = 0
  1170. var fruit = (
  1171. "apple" if count == 2
  1172. else "pear" if count == 1
  1173. else "banana" if count == 0
  1174. else "orange"
  1175. )
  1176. print(fruit) # banana
  1177. # Alternative syntax with backslashes instead of parentheses (for multi-line expressions).
  1178. # Less lines required, but harder to refactor.
  1179. var fruit_alt = \
  1180. "apple" if count == 2 \
  1181. else "pear" if count == 1 \
  1182. else "banana" if count == 0 \
  1183. else "orange"
  1184. print(fruit_alt) # banana
  1185. You may also wish to check if a value is contained within something. You can
  1186. use an ``if`` statement combined with the ``in`` operator to accomplish this::
  1187. # Check if a letter is in a string.
  1188. var text = "abc"
  1189. if 'b' in text: print("The string contains b")
  1190. # Check if a variable is contained within a node.
  1191. if "varName" in get_parent(): print("varName is defined in parent!")
  1192. while
  1193. ~~~~~
  1194. Simple loops are created by using ``while`` syntax. Loops can be broken
  1195. using ``break`` or continued using ``continue`` (which skips to the next
  1196. iteration of the loop without executing any further code in the current iteration):
  1197. ::
  1198. while (expression):
  1199. statement(s)
  1200. for
  1201. ~~~
  1202. To iterate through a range, such as an array or table, a *for* loop is
  1203. used. When iterating over an array, the current array element is stored in
  1204. the loop variable. When iterating over a dictionary, the *key* is stored
  1205. in the loop variable.
  1206. ::
  1207. for x in [5, 7, 11]:
  1208. statement # Loop iterates 3 times with 'x' as 5, then 7 and finally 11.
  1209. var names = ["John", "Marta", "Samantha", "Jimmy"]
  1210. for name: String in names: # Typed loop variable.
  1211. print(name) # Prints name's content.
  1212. var dict = {"a": 0, "b": 1, "c": 2}
  1213. for i in dict:
  1214. print(dict[i]) # Prints 0, then 1, then 2.
  1215. for i in range(3):
  1216. statement # Similar to [0, 1, 2] but does not allocate an array.
  1217. for i in range(1, 3):
  1218. statement # Similar to [1, 2] but does not allocate an array.
  1219. for i in range(2, 8, 2):
  1220. statement # Similar to [2, 4, 6] but does not allocate an array.
  1221. for i in range(8, 2, -2):
  1222. statement # Similar to [8, 6, 4] but does not allocate an array.
  1223. for c in "Hello":
  1224. print(c) # Iterate through all characters in a String, print every letter on new line.
  1225. for i in 3:
  1226. statement # Similar to range(3).
  1227. for i in 2.2:
  1228. statement # Similar to range(ceil(2.2)).
  1229. If you want to assign values on an array as it is being iterated through, it
  1230. is best to use ``for i in array.size()``.
  1231. ::
  1232. for i in array.size():
  1233. array[i] = "Hello World"
  1234. The loop variable is local to the for-loop and assigning to it will not change
  1235. the value on the array. Objects passed by reference (such as nodes) can still
  1236. be manipulated by calling methods on the loop variable.
  1237. ::
  1238. for string in string_array:
  1239. string = "Hello World" # This has no effect
  1240. for node in node_array:
  1241. node.add_to_group("Cool_Group") # This has an effect
  1242. match
  1243. ~~~~~
  1244. A ``match`` statement is used to branch execution of a program.
  1245. It's the equivalent of the ``switch`` statement found in many other languages, but offers some additional features.
  1246. .. warning::
  1247. ``match`` is more type strict than the ``==`` operator. For example ``1`` will **not** match ``1.0``. The only exception is ``String`` vs ``StringName`` matching:
  1248. for example, the String ``"hello"`` is considered equal to the StringName ``&"hello"``.
  1249. Basic syntax
  1250. ^^^^^^^^^^^^
  1251. ::
  1252. match <test value>:
  1253. <pattern(s)>:
  1254. <block>
  1255. <pattern(s)> when <pattern guard>:
  1256. <block>
  1257. <...>
  1258. Crash-course for people who are familiar with switch statements
  1259. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1260. 1. Replace ``switch`` with ``match``.
  1261. 2. Remove ``case``.
  1262. 3. Remove any ``break``\ s.
  1263. 4. Change ``default`` to a single underscore.
  1264. Control flow
  1265. ^^^^^^^^^^^^
  1266. The patterns are matched from top to bottom.
  1267. If a pattern matches, the first corresponding block will be executed. After that, the execution continues below the ``match`` statement.
  1268. .. note::
  1269. The special ``continue`` behavior in ``match`` supported in 3.x was removed in Godot 4.0.
  1270. The following pattern types are available:
  1271. - Literal pattern
  1272. Matches a `literal <Literals_>`_::
  1273. match x:
  1274. 1:
  1275. print("We are number one!")
  1276. 2:
  1277. print("Two are better than one!")
  1278. "test":
  1279. print("Oh snap! It's a string!")
  1280. - Expression pattern
  1281. Matches a constant expression, an identifier, or an attribute access (``A.B``)::
  1282. match typeof(x):
  1283. TYPE_FLOAT:
  1284. print("float")
  1285. TYPE_STRING:
  1286. print("text")
  1287. TYPE_ARRAY:
  1288. print("array")
  1289. - Wildcard pattern
  1290. This pattern matches everything. It's written as a single underscore.
  1291. It can be used as the equivalent of the ``default`` in a ``switch`` statement in other languages::
  1292. match x:
  1293. 1:
  1294. print("It's one!")
  1295. 2:
  1296. print("It's one times two!")
  1297. _:
  1298. print("It's not 1 or 2. I don't care to be honest.")
  1299. - Binding pattern
  1300. A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name.
  1301. It's especially useful in array and dictionary patterns::
  1302. match x:
  1303. 1:
  1304. print("It's one!")
  1305. 2:
  1306. print("It's one times two!")
  1307. var new_var:
  1308. print("It's not 1 or 2, it's ", new_var)
  1309. - Array pattern
  1310. Matches an array. Every single element of the array pattern is a pattern itself, so you can nest them.
  1311. The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  1312. **Open-ended array**: An array can be bigger than the pattern by making the last subpattern ``..``.
  1313. Every subpattern has to be comma-separated.
  1314. ::
  1315. match x:
  1316. []:
  1317. print("Empty array")
  1318. [1, 3, "test", null]:
  1319. print("Very specific array")
  1320. [var start, _, "test"]:
  1321. print("First element is ", start, ", and the last is \"test\"")
  1322. [42, ..]:
  1323. print("Open ended array")
  1324. - Dictionary pattern
  1325. Works in the same way as the array pattern. Every key has to be a constant pattern.
  1326. The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  1327. **Open-ended dictionary**: A dictionary can be bigger than the pattern by making the last subpattern ``..``.
  1328. Every subpattern has to be comma separated.
  1329. If you don't specify a value, then only the existence of the key is checked.
  1330. A value pattern is separated from the key pattern with a ``:``.
  1331. ::
  1332. match x:
  1333. {}:
  1334. print("Empty dict")
  1335. {"name": "Dennis"}:
  1336. print("The name is Dennis")
  1337. {"name": "Dennis", "age": var age}:
  1338. print("Dennis is ", age, " years old.")
  1339. {"name", "age"}:
  1340. print("Has a name and an age, but it's not Dennis :(")
  1341. {"key": "godotisawesome", ..}:
  1342. print("I only checked for one entry and ignored the rest")
  1343. - Multiple patterns
  1344. You can also specify multiple patterns separated by a comma. These patterns aren't allowed to have any bindings in them.
  1345. ::
  1346. match x:
  1347. 1, 2, 3:
  1348. print("It's 1 - 3")
  1349. "Sword", "Splash potion", "Fist":
  1350. print("Yep, you've taken damage")
  1351. Pattern guards
  1352. ^^^^^^^^^^^^^^
  1353. A *pattern guard* is an optional condition that follows the pattern list
  1354. and allows you to make additional checks before choosing a ``match`` branch.
  1355. Unlike a pattern, a pattern guard can be an arbitrary expression.
  1356. Only one branch can be executed per ``match``. Once a branch is chosen, the rest are not checked.
  1357. If you want to use the same pattern for multiple branches or to prevent choosing a branch with too general pattern,
  1358. you can specify a pattern guard after the list of patterns with the ``when`` keyword::
  1359. match point:
  1360. [0, 0]:
  1361. print("Origin")
  1362. [_, 0]:
  1363. print("Point on X-axis")
  1364. [0, _]:
  1365. print("Point on Y-axis")
  1366. [var x, var y] when y == x:
  1367. print("Point on line y = x")
  1368. [var x, var y] when y == -x:
  1369. print("Point on line y = -x")
  1370. [var x, var y]:
  1371. print("Point (%s, %s)" % [x, y])
  1372. - If there is no matching pattern for the current branch, the pattern guard
  1373. is **not** evaluated and the patterns of the next branch are checked.
  1374. - If a matching pattern is found, the pattern guard is evaluated.
  1375. - If it's true, then the body of the branch is executed and ``match`` ends.
  1376. - If it's false, then the patterns of the next branch are checked.
  1377. Classes
  1378. -------
  1379. By default, all script files are unnamed classes. In this case, you can only
  1380. reference them using the file's path, using either a relative or an absolute
  1381. path. For example, if you name a script file ``character.gd``::
  1382. # Inherit from 'character.gd'.
  1383. extends "res://path/to/character.gd"
  1384. # Load character.gd and create a new node instance from it.
  1385. var Character = load("res://path/to/character.gd")
  1386. var character_node = Character.new()
  1387. .. _doc_gdscript_basics_class_name:
  1388. Registering named classes
  1389. ~~~~~~~~~~~~~~~~~~~~~~~~~
  1390. You can give your class a name to register it as a new type in Godot's
  1391. editor. For that, you use the ``class_name`` keyword. You can optionally use
  1392. the ``@icon`` annotation with a path to an image, to use it as an icon. Your
  1393. class will then appear with its new icon in the editor::
  1394. # item.gd
  1395. @icon("res://interface/icons/item.png")
  1396. class_name Item
  1397. extends Node
  1398. .. image:: img/class_name_editor_register_example.png
  1399. .. tip::
  1400. SVG images that are used as custom node icons should have the
  1401. **Editor > Scale With Editor Scale** and **Editor > Convert Icons With Editor Theme**
  1402. :ref:`import options <doc_importing_images_editor_import_options>` enabled. This allows
  1403. icons to follow the editor's scale and theming settings if the icons are designed with
  1404. the same color palette as Godot's own icons.
  1405. Here's a class file example:
  1406. ::
  1407. # Saved as a file named 'character.gd'.
  1408. class_name Character
  1409. var health = 5
  1410. func print_health():
  1411. print(health)
  1412. func print_this_script_three_times():
  1413. print(get_script())
  1414. print(ResourceLoader.load("res://character.gd"))
  1415. print(Character)
  1416. If you want to use ``extends`` too, you can keep both on the same line::
  1417. class_name MyNode extends Node
  1418. .. note::
  1419. Godot initializes non-static variables every time you create an instance,
  1420. and this includes arrays and dictionaries. This is in the spirit of thread safety,
  1421. since scripts can be initialized in separate threads without the user knowing.
  1422. .. warning::
  1423. The Godot editor will hide these custom classes with names that begin with the prefix
  1424. "Editor" in the 'Create New Node' or 'Create New Scene' dialog windows. The classes
  1425. are available for instantiation at runtime via their class names, but are
  1426. automatically hidden by the editor windows along with the built-in editor nodes used
  1427. by the Godot editor.
  1428. Inheritance
  1429. ~~~~~~~~~~~
  1430. A class (stored as a file) can inherit from:
  1431. - A global class.
  1432. - Another class file.
  1433. - An inner class inside another class file.
  1434. Multiple inheritance is not allowed.
  1435. Inheritance uses the ``extends`` keyword::
  1436. # Inherit/extend a globally available class.
  1437. extends SomeClass
  1438. # Inherit/extend a named class file.
  1439. extends "somefile.gd"
  1440. # Inherit/extend an inner class in another file.
  1441. extends "somefile.gd".SomeInnerClass
  1442. .. note::
  1443. If inheritance is not explicitly defined, the class will default to inheriting
  1444. :ref:`class_RefCounted`.
  1445. To check if a given instance inherits from a given class,
  1446. the ``is`` keyword can be used::
  1447. # Cache the enemy class.
  1448. const Enemy = preload("enemy.gd")
  1449. # [...]
  1450. # Use 'is' to check inheritance.
  1451. if entity is Enemy:
  1452. entity.apply_damage()
  1453. To call a function in a *super class* (i.e. one ``extend``-ed in your current
  1454. class), use the ``super`` keyword::
  1455. super(args)
  1456. This is especially useful because functions in extending classes replace
  1457. functions with the same name in their super classes. If you still want to
  1458. call them, you can use ``super``::
  1459. func some_func(x):
  1460. super(x) # Calls the same function on the super class.
  1461. If you need to call a different function from the super class, you can specify
  1462. the function name with the attribute operator::
  1463. func overriding():
  1464. return 0 # This overrides the method in the base class.
  1465. func dont_override():
  1466. return super.overriding() # This calls the method as defined in the base class.
  1467. .. warning::
  1468. One of the common misconceptions is trying to override *non-virtual* engine methods
  1469. such as ``get_class()``, ``queue_free()``, etc. This is not supported for technical reasons.
  1470. In Godot 3, you can *shadow* engine methods in GDScript, and it will work if you call this method in GDScript.
  1471. However, the engine will **not** execute your code if the method is called inside the engine on some event.
  1472. In Godot 4, even shadowing may not always work, as GDScript optimizes native method calls.
  1473. Therefore, we added the ``NATIVE_METHOD_OVERRIDE`` warning, which is treated as an error by default.
  1474. We strongly advise against disabling or ignoring the warning.
  1475. Note that this does not apply to virtual methods such as ``_ready()``, ``_process()`` and others
  1476. (marked with the ``virtual`` qualifier in the documentation and the names start with an underscore).
  1477. These methods are specifically for customizing engine behavior and can be overridden in GDScript.
  1478. Signals and notifications can also be useful for these purposes.
  1479. Class constructor
  1480. ~~~~~~~~~~~~~~~~~
  1481. The class constructor, called on class instantiation, is named ``_init``. If you
  1482. want to call the base class constructor, you can also use the ``super`` syntax.
  1483. Note that every class has an implicit constructor that is always called
  1484. (defining the default values of class variables). ``super`` is used to call the
  1485. explicit constructor::
  1486. func _init(arg):
  1487. super("some_default", arg) # Call the custom base constructor.
  1488. This is better explained through examples. Consider this scenario::
  1489. # state.gd (inherited class).
  1490. var entity = null
  1491. var message = null
  1492. func _init(e=null):
  1493. entity = e
  1494. func enter(m):
  1495. message = m
  1496. # idle.gd (inheriting class).
  1497. extends "state.gd"
  1498. func _init(e=null, m=null):
  1499. super(e)
  1500. # Do something with 'e'.
  1501. message = m
  1502. There are a few things to keep in mind here:
  1503. 1. If the inherited class (``state.gd``) defines a ``_init`` constructor that takes
  1504. arguments (``e`` in this case), then the inheriting class (``idle.gd``) *must*
  1505. define ``_init`` as well and pass appropriate parameters to ``_init`` from ``state.gd``.
  1506. 2. ``idle.gd`` can have a different number of arguments than the base class ``state.gd``.
  1507. 3. In the example above, ``e`` passed to the ``state.gd`` constructor is the same ``e`` passed
  1508. in to ``idle.gd``.
  1509. 4. If ``idle.gd``'s ``_init`` constructor takes 0 arguments, it still needs to pass some value
  1510. to the ``state.gd`` base class, even if it does nothing. This brings us to the fact that you
  1511. can pass expressions to the base constructor as well, not just variables, e.g.::
  1512. # idle.gd
  1513. func _init():
  1514. super(5)
  1515. Static constructor
  1516. ~~~~~~~~~~~~~~~~~~
  1517. A static constructor is a static function ``_static_init`` that is called automatically
  1518. when the class is loaded, after the static variables have been initialized::
  1519. static var my_static_var = 1
  1520. static func _static_init():
  1521. my_static_var = 2
  1522. A static constructor cannot take arguments and must not return any value.
  1523. .. _doc_gdscript_basics_inner_classes:
  1524. Inner classes
  1525. ~~~~~~~~~~~~~
  1526. A class file can contain inner classes. Inner classes are defined using the
  1527. ``class`` keyword. They are instanced using the ``ClassName.new()``
  1528. function.
  1529. ::
  1530. # Inside a class file.
  1531. # An inner class in this class file.
  1532. class SomeInnerClass:
  1533. var a = 5
  1534. func print_value_of_a():
  1535. print(a)
  1536. # This is the constructor of the class file's main class.
  1537. func _init():
  1538. var c = SomeInnerClass.new()
  1539. c.print_value_of_a()
  1540. .. _doc_gdscript_classes_as_resources:
  1541. Classes as resources
  1542. ~~~~~~~~~~~~~~~~~~~~
  1543. Classes stored as files are treated as :ref:`GDScripts <class_GDScript>`. They
  1544. must be loaded from disk to access them in other classes. This is done using
  1545. either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
  1546. class resource is done by calling the ``new`` function on the class object::
  1547. # Load the class resource when calling load().
  1548. var MyClass = load("myclass.gd")
  1549. # Preload the class only once at compile time.
  1550. const MyClass = preload("myclass.gd")
  1551. func _init():
  1552. var a = MyClass.new()
  1553. a.some_function()
  1554. Exports
  1555. -------
  1556. .. note::
  1557. Documentation about exports has been moved to :ref:`doc_gdscript_exports`.
  1558. .. _doc_gdscript_basics_setters_getters:
  1559. Properties (setters and getters)
  1560. --------------------------------
  1561. Sometimes, you want a class' member variable to do more than just hold data and actually perform
  1562. some validation or computation whenever its value changes. It may also be desired to
  1563. encapsulate its access in some way.
  1564. For this, GDScript provides a special syntax to define properties using the ``set`` and ``get``
  1565. keywords after a variable declaration. Then you can define a code block that will be executed
  1566. when the variable is accessed or assigned.
  1567. Example::
  1568. var milliseconds: int = 0
  1569. var seconds: int:
  1570. get:
  1571. return milliseconds / 1000
  1572. set(value):
  1573. milliseconds = value * 1000
  1574. .. note::
  1575. Unlike ``setget`` in previous Godot versions, ``set`` and ``get`` methods are **always** called (except as noted below),
  1576. even when accessed inside the same class (with or without prefixing with ``self.``). This makes the behavior
  1577. consistent. If you need direct access to the value, use another variable for direct access and make the property
  1578. code use that name.
  1579. Alternative syntax
  1580. ~~~~~~~~~~~~~~~~~~
  1581. Also there is another notation to use existing class functions if you want to split the code from the variable declaration
  1582. or you need to reuse the code across multiple properties (but you can't distinguish which property the setter/getter is being called for)::
  1583. var my_prop:
  1584. get = get_my_prop, set = set_my_prop
  1585. This can also be done in the same line::
  1586. var my_prop: get = get_my_prop, set = set_my_prop
  1587. The setter and getter must use the same notation, mixing styles for the same variable is not allowed.
  1588. .. note::
  1589. You cannot specify type hints for *inline* setters and getters. This is done on purpose to reduce the boilerplate.
  1590. If the variable is typed, then the setter's argument is automatically of the same type, and the getter's return value must match it.
  1591. Separated setter/getter functions can have type hints, and the type must match the variable's type or be a wider type.
  1592. When setter/getter is not called
  1593. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1594. When a variable is initialized, the value of the initializer will be written directly to the variable.
  1595. Including if the ``@onready`` annotation is applied to the variable.
  1596. Using the variable's name to set it inside its own setter or to get it inside its own getter will directly access the underlying member,
  1597. so it won't generate infinite recursion and saves you from explicitly declaring another variable::
  1598. signal changed(new_value)
  1599. var warns_when_changed = "some value":
  1600. get:
  1601. return warns_when_changed
  1602. set(value):
  1603. changed.emit(value)
  1604. warns_when_changed = value
  1605. This also applies to the alternative syntax::
  1606. var my_prop: set = set_my_prop
  1607. func set_my_prop(value):
  1608. my_prop = value # No infinite recursion.
  1609. .. warning::
  1610. The exception does **not** propagate to other functions called in the setter/getter.
  1611. For example, the following code **will** cause an infinite recursion::
  1612. var my_prop:
  1613. set(value):
  1614. set_my_prop(value)
  1615. func set_my_prop(value):
  1616. my_prop = value # Infinite recursion, since `set_my_prop()` is not the setter.
  1617. .. _doc_gdscript_tool_mode:
  1618. Tool mode
  1619. ---------
  1620. By default, scripts don't run inside the editor and only the exported
  1621. properties can be changed. In some cases, it is desired that they do run
  1622. inside the editor (as long as they don't execute game code or manually
  1623. avoid doing so). For this, the ``@tool`` annotation exists and must be
  1624. placed at the top of the file::
  1625. @tool
  1626. extends Button
  1627. func _ready():
  1628. print("Hello")
  1629. See :ref:`doc_running_code_in_the_editor` for more information.
  1630. .. warning:: Be cautious when freeing nodes with ``queue_free()`` or ``free()``
  1631. in a tool script (especially the script's owner itself). As tool
  1632. scripts run their code in the editor, misusing them may lead to
  1633. crashing the editor.
  1634. .. _doc_gdscript_basics_memory_management:
  1635. Memory management
  1636. -----------------
  1637. Godot implements reference counting to free certain instances that are no longer
  1638. used, instead of a garbage collector, or requiring purely manual management.
  1639. Any instance of the :ref:`class_RefCounted` class (or any class that inherits
  1640. it, such as :ref:`class_Resource`) will be freed automatically when no longer
  1641. in use. For an instance of any class that is not a :ref:`class_RefCounted`
  1642. (such as :ref:`class_Node` or the base :ref:`class_Object` type), it will
  1643. remain in memory until it is deleted with ``free()`` (or ``queue_free()``
  1644. for Nodes).
  1645. .. note::
  1646. If a :ref:`class_Node` is deleted via ``free()`` or ``queue_free()``,
  1647. all of its children will also recursively be deleted.
  1648. To avoid reference cycles that can't be freed, a :ref:`class_WeakRef`
  1649. function is provided for creating weak references, which allow access
  1650. to the object without preventing a :ref:`class_RefCounted` from freeing.
  1651. Here is an example:
  1652. ::
  1653. extends Node
  1654. var my_file_ref
  1655. func _ready():
  1656. var f = FileAccess.open("user://example_file.json", FileAccess.READ)
  1657. my_file_ref = weakref(f)
  1658. # the FileAccess class inherits RefCounted, so it will be freed when not in use
  1659. # the WeakRef will not prevent f from being freed when other_node is finished
  1660. other_node.use_file(f)
  1661. func _this_is_called_later():
  1662. var my_file = my_file_ref.get_ref()
  1663. if my_file:
  1664. my_file.close()
  1665. Alternatively, when not using references, the
  1666. ``is_instance_valid(instance)`` can be used to check if an object has been
  1667. freed.
  1668. .. _doc_gdscript_signals:
  1669. Signals
  1670. -------
  1671. Signals are a tool to emit messages from an object that other objects can react
  1672. to. To create custom signals for a class, use the ``signal`` keyword.
  1673. ::
  1674. extends Node
  1675. # A signal named health_depleted.
  1676. signal health_depleted
  1677. .. note::
  1678. Signals are a `Callback
  1679. <https://en.wikipedia.org/wiki/Callback_(computer_programming)>`_
  1680. mechanism. They also fill the role of Observers, a common programming
  1681. pattern. For more information, read the `Observer tutorial
  1682. <https://gameprogrammingpatterns.com/observer.html>`_ in the
  1683. Game Programming Patterns ebook.
  1684. You can connect these signals to methods the same way you connect built-in
  1685. signals of nodes like :ref:`class_Button` or :ref:`class_RigidBody3D`.
  1686. In the example below, we connect the ``health_depleted`` signal from a
  1687. ``Character`` node to a ``Game`` node. When the ``Character`` node emits the
  1688. signal, the game node's ``_on_character_health_depleted`` is called::
  1689. # game.gd
  1690. func _ready():
  1691. var character_node = get_node('Character')
  1692. character_node.health_depleted.connect(_on_character_health_depleted)
  1693. func _on_character_health_depleted():
  1694. get_tree().reload_current_scene()
  1695. You can emit as many arguments as you want along with a signal.
  1696. Here is an example where this is useful. Let's say we want a life bar on screen
  1697. to react to health changes with an animation, but we want to keep the user
  1698. interface separate from the player in our scene tree.
  1699. In our ``character.gd`` script, we define a ``health_changed`` signal and emit
  1700. it with :ref:`Signal.emit() <class_Signal_method_emit>`, and from
  1701. a ``Game`` node higher up our scene tree, we connect it to the ``Lifebar`` using
  1702. the :ref:`Signal.connect() <class_Signal_method_connect>` method::
  1703. # character.gd
  1704. ...
  1705. signal health_changed
  1706. func take_damage(amount):
  1707. var old_health = health
  1708. health -= amount
  1709. # We emit the health_changed signal every time the
  1710. # character takes damage.
  1711. health_changed.emit(old_health, health)
  1712. ...
  1713. ::
  1714. # lifebar.gd
  1715. # Here, we define a function to use as a callback when the
  1716. # character's health_changed signal is emitted.
  1717. ...
  1718. func _on_Character_health_changed(old_value, new_value):
  1719. if old_value > new_value:
  1720. progress_bar.modulate = Color.RED
  1721. else:
  1722. progress_bar.modulate = Color.GREEN
  1723. # Imagine that `animate` is a user-defined function that animates the
  1724. # bar filling up or emptying itself.
  1725. progress_bar.animate(old_value, new_value)
  1726. ...
  1727. In the ``Game`` node, we get both the ``Character`` and ``Lifebar`` nodes, then
  1728. connect the character, that emits the signal, to the receiver, the ``Lifebar``
  1729. node in this case.
  1730. ::
  1731. # game.gd
  1732. func _ready():
  1733. var character_node = get_node('Character')
  1734. var lifebar_node = get_node('UserInterface/Lifebar')
  1735. character_node.health_changed.connect(lifebar_node._on_Character_health_changed)
  1736. This allows the ``Lifebar`` to react to health changes without coupling it to
  1737. the ``Character`` node.
  1738. You can write optional argument names in parentheses after the signal's
  1739. definition::
  1740. # Defining a signal that forwards two arguments.
  1741. signal health_changed(old_value, new_value)
  1742. These arguments show up in the editor's node dock, and Godot can use them to
  1743. generate callback functions for you. However, you can still emit any number of
  1744. arguments when you emit signals; it's up to you to emit the correct values.
  1745. .. image:: img/gdscript_basics_signals_node_tab_1.png
  1746. GDScript can bind an array of values to connections between a signal
  1747. and a method. When the signal is emitted, the callback method receives
  1748. the bound values. These bound arguments are unique to each connection,
  1749. and the values will stay the same.
  1750. You can use this array of values to add extra constant information to the
  1751. connection if the emitted signal itself doesn't give you access to all the data
  1752. that you need.
  1753. Building on the example above, let's say we want to display a log of the damage
  1754. taken by each character on the screen, like ``Player1 took 22 damage.``. The
  1755. ``health_changed`` signal doesn't give us the name of the character that took
  1756. damage. So when we connect the signal to the in-game console, we can add the
  1757. character's name in the binds array argument::
  1758. # game.gd
  1759. func _ready():
  1760. var character_node = get_node('Character')
  1761. var battle_log_node = get_node('UserInterface/BattleLog')
  1762. character_node.health_changed.connect(battle_log_node._on_Character_health_changed.bind(character_node.name))
  1763. Our ``BattleLog`` node receives each element in the binds array as an extra argument::
  1764. # battle_log.gd
  1765. func _on_Character_health_changed(old_value, new_value, character_name):
  1766. if not new_value <= old_value:
  1767. return
  1768. var damage = old_value - new_value
  1769. label.text += character_name + " took " + str(damage) + " damage."
  1770. Awaiting signals or coroutines
  1771. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1772. The ``await`` keyword can be used to create `coroutines <https://en.wikipedia.org/wiki/Coroutine>`_
  1773. which wait until a signal is emitted before continuing execution. Using the ``await`` keyword with a signal or a
  1774. call to a function that is also a coroutine will immediately return the control to the caller. When the signal is
  1775. emitted (or the called coroutine finishes), it will resume execution from the point on where it stopped.
  1776. For example, to stop execution until the user presses a button, you can do something like this::
  1777. func wait_confirmation():
  1778. print("Prompting user")
  1779. await $Button.button_up # Waits for the button_up signal from Button node.
  1780. print("User confirmed")
  1781. return true
  1782. In this case, the ``wait_confirmation`` becomes a coroutine, which means that the caller also needs to await it::
  1783. func request_confirmation():
  1784. print("Will ask the user")
  1785. var confirmed = await wait_confirmation()
  1786. if confirmed:
  1787. print("User confirmed")
  1788. else:
  1789. print("User cancelled")
  1790. Note that requesting a coroutine's return value without ``await`` will trigger an error::
  1791. func wrong():
  1792. var confirmed = wait_confirmation() # Will give an error.
  1793. However, if you don't depend on the result, you can just call it asynchronously, which won't stop execution and won't
  1794. make the current function a coroutine::
  1795. func okay():
  1796. wait_confirmation()
  1797. print("This will be printed immediately, before the user press the button.")
  1798. If you use await with an expression that isn't a signal nor a coroutine, the value will be returned immediately and the
  1799. function won't give the control back to the caller::
  1800. func no_wait():
  1801. var x = await get_five()
  1802. print("This doesn't make this function a coroutine.")
  1803. func get_five():
  1804. return 5
  1805. This also means that returning a signal from a function that isn't a coroutine will make the caller await that signal::
  1806. func get_signal():
  1807. return $Button.button_up
  1808. func wait_button():
  1809. await get_signal()
  1810. print("Button was pressed")
  1811. .. note:: Unlike ``yield`` in previous Godot versions, you cannot obtain the function state object.
  1812. This is done to ensure type safety.
  1813. With this type safety in place, a function cannot say that it returns an ``int`` while it actually returns a function state object
  1814. during runtime.
  1815. Assert keyword
  1816. --------------
  1817. The ``assert`` keyword can be used to check conditions in debug builds. These
  1818. assertions are ignored in non-debug builds. This means that the expression
  1819. passed as argument won't be evaluated in a project exported in release mode.
  1820. Due to this, assertions must **not** contain expressions that have
  1821. side effects. Otherwise, the behavior of the script would vary
  1822. depending on whether the project is run in a debug build.
  1823. ::
  1824. # Check that 'i' is 0. If 'i' is not 0, an assertion error will occur.
  1825. assert(i == 0)
  1826. When running a project from the editor, the project will be paused if an
  1827. assertion error occurs.
  1828. You can optionally pass a custom error message to be shown if the assertion
  1829. fails::
  1830. assert(enemy_power < 256, "Enemy is too powerful!")