gdscript_basics.rst 91 KB

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