gdscript_basics.rst 75 KB

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