gdscript_basics.rst 98 KB

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