gdscript_basics.rst 85 KB

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