gdscript_basics.rst 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  1. .. _doc_gdscript:
  2. GDScript basics
  3. ===============
  4. Introduction
  5. ------------
  6. *GDScript* is a high-level, dynamically typed programming language used to
  7. create content. It uses a syntax similar to
  8. `Python <https://en.wikipedia.org/wiki/Python_%28programming_language%29>`_
  9. (blocks are indent-based and many keywords are similar). Its goal is
  10. to be optimized for and tightly integrated with Godot Engine, allowing great
  11. flexibility for content creation and integration.
  12. History
  13. ~~~~~~~
  14. .. note::
  15. Documentation about GDScript's history has been moved to the
  16. :ref:`Frequently Asked Questions <doc_faq_what_is_gdscript>`.
  17. Example of GDScript
  18. ~~~~~~~~~~~~~~~~~~~
  19. Some people can learn better by taking a look at the syntax, so
  20. here's a simple example of how GDScript looks.
  21. ::
  22. # A file is a class!
  23. # Inheritance
  24. extends BaseClass
  25. # (optional) class definition with a custom icon
  26. class_name MyClass, "res://path/to/optional/icon.svg"
  27. # Member variables
  28. var a = 5
  29. var s = "Hello"
  30. var arr = [1, 2, 3]
  31. var dict = {"key": "value", 2: 3}
  32. var typed_var: int
  33. var inferred_type := "String"
  34. # Constants
  35. const ANSWER = 42
  36. const THE_NAME = "Charly"
  37. # Enums
  38. enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
  39. enum Named {THING_1, THING_2, ANOTHER_THING = -1}
  40. # Built-in vector types
  41. var v2 = Vector2(1, 2)
  42. var v3 = Vector3(1, 2, 3)
  43. # Function
  44. func some_function(param1, param2):
  45. var local_var = 5
  46. if param1 < local_var:
  47. print(param1)
  48. elif param2 > 5:
  49. print(param2)
  50. else:
  51. print("Fail!")
  52. for i in range(20):
  53. print(i)
  54. while param2 != 0:
  55. param2 -= 1
  56. var local_var2 = param1 + 3
  57. return local_var2
  58. # Functions override functions with the same name on the base/parent class.
  59. # If you still want to call them, use '.' (like 'super' in other languages).
  60. func something(p1, p2):
  61. .something(p1, p2)
  62. # Inner class
  63. class Something:
  64. var a = 10
  65. # Constructor
  66. func _init():
  67. print("Constructed!")
  68. var lv = Something.new()
  69. print(lv.a)
  70. If you have previous experience with statically typed languages such as
  71. C, C++, or C# but never used a dynamically typed one before, it is advised you
  72. read this tutorial: :ref:`doc_gdscript_more_efficiently`.
  73. Language
  74. --------
  75. In the following, an overview is given to GDScript. Details, such as which
  76. methods are available to arrays or other objects, should be looked up in
  77. the linked class descriptions.
  78. Identifiers
  79. ~~~~~~~~~~~
  80. Any string that restricts itself to alphabetic characters (``a`` to
  81. ``z`` and ``A`` to ``Z``), digits (``0`` to ``9``) and ``_`` qualifies
  82. as an identifier. Additionally, identifiers must not begin with a digit.
  83. Identifiers are case-sensitive (``foo`` is different from ``FOO``).
  84. Keywords
  85. ~~~~~~~~
  86. The following is the list of keywords supported by the language. Since
  87. keywords are reserved words (tokens), they can't be used as identifiers.
  88. Operators (like ``in``, ``not``, ``and`` or ``or``) and names of built-in types
  89. as listed in the following sections are also reserved.
  90. Keywords are defined in the `GDScript tokenizer <https://github.com/godotengine/godot/blob/master/modules/gdscript/gdscript_tokenizer.cpp>`_
  91. in case you want to take a look under the hood.
  92. +------------+---------------------------------------------------------------------------------------------------------------+
  93. | Keyword | Description |
  94. +============+===============================================================================================================+
  95. | if | See `if/else/elif`_. |
  96. +------------+---------------------------------------------------------------------------------------------------------------+
  97. | elif | See `if/else/elif`_. |
  98. +------------+---------------------------------------------------------------------------------------------------------------+
  99. | else | See `if/else/elif`_. |
  100. +------------+---------------------------------------------------------------------------------------------------------------+
  101. | for | See for_. |
  102. +------------+---------------------------------------------------------------------------------------------------------------+
  103. | while | See while_. |
  104. +------------+---------------------------------------------------------------------------------------------------------------+
  105. | match | See match_. |
  106. +------------+---------------------------------------------------------------------------------------------------------------+
  107. | break | Exits the execution of the current ``for`` or ``while`` loop. |
  108. +------------+---------------------------------------------------------------------------------------------------------------+
  109. | continue | Immediately skips to the next iteration of the ``for`` or ``while`` loop. |
  110. +------------+---------------------------------------------------------------------------------------------------------------+
  111. | pass | Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions. |
  112. +------------+---------------------------------------------------------------------------------------------------------------+
  113. | return | Returns a value from a function. |
  114. +------------+---------------------------------------------------------------------------------------------------------------+
  115. | class | Defines a class. |
  116. +------------+---------------------------------------------------------------------------------------------------------------+
  117. | extends | Defines what class to extend with the current class. |
  118. +------------+---------------------------------------------------------------------------------------------------------------+
  119. | is | Tests whether a variable extends a given class, or is of a given built-in type. |
  120. +------------+---------------------------------------------------------------------------------------------------------------+
  121. | as | Cast the value to a given type if possible. |
  122. +------------+---------------------------------------------------------------------------------------------------------------+
  123. | self | Refers to current class instance. |
  124. +------------+---------------------------------------------------------------------------------------------------------------+
  125. | tool | Executes the script in the editor. |
  126. +------------+---------------------------------------------------------------------------------------------------------------+
  127. | signal | Defines a signal. |
  128. +------------+---------------------------------------------------------------------------------------------------------------+
  129. | func | Defines a function. |
  130. +------------+---------------------------------------------------------------------------------------------------------------+
  131. | static | Defines a static function. Static member variables are not allowed. |
  132. +------------+---------------------------------------------------------------------------------------------------------------+
  133. | const | Defines a constant. |
  134. +------------+---------------------------------------------------------------------------------------------------------------+
  135. | enum | Defines an enum. |
  136. +------------+---------------------------------------------------------------------------------------------------------------+
  137. | var | Defines a variable. |
  138. +------------+---------------------------------------------------------------------------------------------------------------+
  139. | onready | Initializes a variable once the Node the script is attached to and its children are part of the scene tree. |
  140. +------------+---------------------------------------------------------------------------------------------------------------+
  141. | export | Saves a variable along with the resource it's attached to and makes it visible and modifiable in the editor. |
  142. +------------+---------------------------------------------------------------------------------------------------------------+
  143. | setget | Defines setter and getter functions for a variable. |
  144. +------------+---------------------------------------------------------------------------------------------------------------+
  145. | breakpoint | Editor helper for debugger breakpoints. |
  146. +------------+---------------------------------------------------------------------------------------------------------------+
  147. | preload | Preloads a class or variable. See `Classes as resources`_. |
  148. +------------+---------------------------------------------------------------------------------------------------------------+
  149. | yield | Coroutine support. See `Coroutines with yield`_. |
  150. +------------+---------------------------------------------------------------------------------------------------------------+
  151. | assert | Asserts a condition, logs error on failure. Ignored in non-debug builds. See `Assert keyword`_. |
  152. +------------+---------------------------------------------------------------------------------------------------------------+
  153. | remote | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  154. +------------+---------------------------------------------------------------------------------------------------------------+
  155. | master | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  156. +------------+---------------------------------------------------------------------------------------------------------------+
  157. | puppet | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  158. +------------+---------------------------------------------------------------------------------------------------------------+
  159. | remotesync | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  160. +------------+---------------------------------------------------------------------------------------------------------------+
  161. | mastersync | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  162. +------------+---------------------------------------------------------------------------------------------------------------+
  163. | puppetsync | Networking RPC annotation. See :ref:`high-level multiplayer docs <doc_high_level_multiplayer>`. |
  164. +------------+---------------------------------------------------------------------------------------------------------------+
  165. | PI | PI constant. |
  166. +------------+---------------------------------------------------------------------------------------------------------------+
  167. | TAU | TAU constant. |
  168. +------------+---------------------------------------------------------------------------------------------------------------+
  169. | INF | Infinity constant. Used for comparisons. |
  170. +------------+---------------------------------------------------------------------------------------------------------------+
  171. | NAN | NAN (not a number) constant. Used for comparisons. |
  172. +------------+---------------------------------------------------------------------------------------------------------------+
  173. Operators
  174. ~~~~~~~~~
  175. The following is the list of supported operators and their precedence.
  176. +---------------------------------------------------------------+-----------------------------------------+
  177. | **Operator** | **Description** |
  178. +---------------------------------------------------------------+-----------------------------------------+
  179. | ``x[index]`` | Subscription (highest priority) |
  180. +---------------------------------------------------------------+-----------------------------------------+
  181. | ``x.attribute`` | Attribute reference |
  182. +---------------------------------------------------------------+-----------------------------------------+
  183. | ``foo()`` | Function call |
  184. +---------------------------------------------------------------+-----------------------------------------+
  185. | ``is`` | Instance type checker |
  186. +---------------------------------------------------------------+-----------------------------------------+
  187. | ``~`` | Bitwise NOT |
  188. +---------------------------------------------------------------+-----------------------------------------+
  189. | ``-x`` | Negative / Unary negation |
  190. +---------------------------------------------------------------+-----------------------------------------+
  191. | ``*`` ``/`` ``%`` | Multiplication / Division / Remainder |
  192. | | |
  193. | | These operators have the same behavior |
  194. | | as C++. Integer division is truncated |
  195. | | rather than returning a fractional |
  196. | | number, and the % operator is only |
  197. | | available for ints ("fmod" for floats) |
  198. +---------------------------------------------------------------+-----------------------------------------+
  199. | ``+`` | Addition / Concatenation of arrays |
  200. +---------------------------------------------------------------+-----------------------------------------+
  201. | ``-`` | Subtraction |
  202. +---------------------------------------------------------------+-----------------------------------------+
  203. | ``<<`` ``>>`` | Bit shifting |
  204. +---------------------------------------------------------------+-----------------------------------------+
  205. | ``&`` | Bitwise AND |
  206. +---------------------------------------------------------------+-----------------------------------------+
  207. | ``^`` | Bitwise XOR |
  208. +---------------------------------------------------------------+-----------------------------------------+
  209. | ``|`` | Bitwise OR |
  210. +---------------------------------------------------------------+-----------------------------------------+
  211. | ``<`` ``>`` ``==`` ``!=`` ``>=`` ``<=`` | Comparisons |
  212. +---------------------------------------------------------------+-----------------------------------------+
  213. | ``in`` | Content test |
  214. +---------------------------------------------------------------+-----------------------------------------+
  215. | ``!`` ``not`` | Boolean NOT |
  216. +---------------------------------------------------------------+-----------------------------------------+
  217. | ``and`` ``&&`` | Boolean AND |
  218. +---------------------------------------------------------------+-----------------------------------------+
  219. | ``or`` ``||`` | Boolean OR |
  220. +---------------------------------------------------------------+-----------------------------------------+
  221. | ``if x else`` | Ternary if/else |
  222. +---------------------------------------------------------------+-----------------------------------------+
  223. | ``as`` | Type casting |
  224. +---------------------------------------------------------------+-----------------------------------------+
  225. | ``=`` ``+=`` ``-=`` ``*=`` ``/=`` ``%=`` ``&=`` ``|=`` | Assignment (lowest priority) |
  226. +---------------------------------------------------------------+-----------------------------------------+
  227. Literals
  228. ~~~~~~~~
  229. +--------------------------+----------------------------------------+
  230. | **Literal** | **Type** |
  231. +--------------------------+----------------------------------------+
  232. | ``45`` | Base 10 integer |
  233. +--------------------------+----------------------------------------+
  234. | ``0x8F51`` | Base 16 (hexadecimal) integer |
  235. +--------------------------+----------------------------------------+
  236. | ``0b101010`` | Base 2 (binary) integer |
  237. +--------------------------+----------------------------------------+
  238. | ``3.14``, ``58.1e-10`` | Floating-point number (real) |
  239. +--------------------------+----------------------------------------+
  240. | ``"Hello"``, ``"Hi"`` | Strings |
  241. +--------------------------+----------------------------------------+
  242. | ``"""Hello"""`` | Multiline string |
  243. +--------------------------+----------------------------------------+
  244. | ``@"Node/Label"`` | :ref:`class_NodePath` or StringName |
  245. +--------------------------+----------------------------------------+
  246. | ``$NodePath`` | Shorthand for ``get_node("NodePath")`` |
  247. +--------------------------+----------------------------------------+
  248. Comments
  249. ~~~~~~~~
  250. Anything from a ``#`` to the end of the line is ignored and is
  251. considered a comment.
  252. ::
  253. # This is a comment.
  254. .. _doc_gdscript_builtin_types:
  255. Built-in types
  256. --------------
  257. Built-in types are stack-allocated. They are passed as values. This means a copy
  258. is created on each assignment or when passing them as arguments to functions.
  259. The only exceptions are ``Array``\ s and ``Dictionaries``, which are passed by
  260. reference so they are shared. (Pooled arrays such as ``PackedByteArray`` are still
  261. passed as values.)
  262. Basic built-in types
  263. ~~~~~~~~~~~~~~~~~~~~
  264. A variable in GDScript can be assigned to several built-in types.
  265. null
  266. ^^^^
  267. ``null`` is an empty data type that contains no information and can not
  268. be assigned any other value.
  269. :ref:`bool <class_bool>`
  270. ^^^^^^^^^^^^^^^^^^^^^^^^
  271. Short for "boolean", it can only contain ``true`` or ``false``.
  272. :ref:`int <class_int>`
  273. ^^^^^^^^^^^^^^^^^^^^^^
  274. Short for "integer", it stores whole numbers (positive and negative).
  275. It is stored as a 64-bit value, equivalent to "int64_t" in C++.
  276. :ref:`float <class_float>`
  277. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  278. Stores real numbers, including decimals, using floating-point values.
  279. It is stored as a 64-bit value, equivalent to "double" in C++.
  280. Note: Currently, data structures such as Vector2, Vector3, and
  281. PackedFloat32Array store 32-bit single-precision "float" values.
  282. :ref:`String <class_String>`
  283. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  284. A sequence of characters in `Unicode format <https://en.wikipedia.org/wiki/Unicode>`_.
  285. Strings can contain the following escape sequences:
  286. +---------------------+---------------------------------+
  287. | **Escape sequence** | **Expands to** |
  288. +---------------------+---------------------------------+
  289. | ``\n`` | Newline (line feed) |
  290. +---------------------+---------------------------------+
  291. | ``\t`` | Horizontal tab character |
  292. +---------------------+---------------------------------+
  293. | ``\r`` | Carriage return |
  294. +---------------------+---------------------------------+
  295. | ``\a`` | Alert (beep/bell) |
  296. +---------------------+---------------------------------+
  297. | ``\b`` | Backspace |
  298. +---------------------+---------------------------------+
  299. | ``\f`` | Formfeed page break |
  300. +---------------------+---------------------------------+
  301. | ``\v`` | Vertical tab character |
  302. +---------------------+---------------------------------+
  303. | ``\"`` | Double quote |
  304. +---------------------+---------------------------------+
  305. | ``\'`` | Single quote |
  306. +---------------------+---------------------------------+
  307. | ``\\`` | Backslash |
  308. +---------------------+---------------------------------+
  309. | ``\uXXXX`` | Unicode codepoint ``XXXX`` |
  310. | | (hexadecimal, case-insensitive) |
  311. +---------------------+---------------------------------+
  312. GDScript also supports :ref:`doc_gdscript_printf`.
  313. Vector built-in types
  314. ~~~~~~~~~~~~~~~~~~~~~
  315. :ref:`Vector2 <class_Vector2>`
  316. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  317. 2D vector type containing ``x`` and ``y`` fields. Can also be
  318. accessed as an array.
  319. :ref:`Rect2 <class_Rect2>`
  320. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  321. 2D Rectangle type containing two vectors fields: ``position`` and ``size``.
  322. Also contains an ``end`` field which is ``position + size``.
  323. :ref:`Vector3 <class_Vector3>`
  324. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  325. 3D vector type containing ``x``, ``y`` and ``z`` fields. This can also
  326. be accessed as an array.
  327. :ref:`Transform2D <class_Transform2D>`
  328. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  329. 3×2 matrix used for 2D transforms.
  330. :ref:`Plane <class_Plane>`
  331. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  332. 3D Plane type in normalized form that contains a ``normal`` vector field
  333. and a ``d`` scalar distance.
  334. :ref:`Quat <class_Quat>`
  335. ^^^^^^^^^^^^^^^^^^^^^^^^
  336. Quaternion is a datatype used for representing a 3D rotation. It's
  337. useful for interpolating rotations.
  338. :ref:`AABB <class_AABB>`
  339. ^^^^^^^^^^^^^^^^^^^^^^^^
  340. Axis-aligned bounding box (or 3D box) contains 2 vectors fields: ``position``
  341. and ``size``. Also contains an ``end`` field which is
  342. ``position + size``.
  343. :ref:`Basis <class_Basis>`
  344. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  345. 3x3 matrix used for 3D rotation and scale. It contains 3 vector fields
  346. (``x``, ``y`` and ``z``) and can also be accessed as an array of 3D
  347. vectors.
  348. :ref:`Transform <class_Transform>`
  349. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  350. 3D Transform contains a Basis field ``basis`` and a Vector3 field
  351. ``origin``.
  352. Engine built-in types
  353. ~~~~~~~~~~~~~~~~~~~~~
  354. :ref:`Color <class_Color>`
  355. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  356. Color data type contains ``r``, ``g``, ``b``, and ``a`` fields. It can
  357. also be accessed as ``h``, ``s``, and ``v`` for hue/saturation/value.
  358. :ref:`NodePath <class_NodePath>`
  359. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  360. Compiled path to a node used mainly in the scene system. It can be
  361. easily assigned to, and from, a String.
  362. :ref:`RID <class_RID>`
  363. ^^^^^^^^^^^^^^^^^^^^^^
  364. Resource ID (RID). Servers use generic RIDs to reference opaque data.
  365. :ref:`Object <class_Object>`
  366. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  367. Base class for anything that is not a built-in type.
  368. Container built-in types
  369. ~~~~~~~~~~~~~~~~~~~~~~~~
  370. :ref:`Array <class_Array>`
  371. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  372. Generic sequence of arbitrary object types, including other arrays or dictionaries (see below).
  373. The array can resize dynamically. Arrays are indexed starting from index ``0``.
  374. Negative indices count from the end.
  375. ::
  376. var arr = []
  377. arr = [1, 2, 3]
  378. var b = arr[1] # This is 2.
  379. var c = arr[arr.size() - 1] # This is 3.
  380. var d = arr[-1] # Same as the previous line, but shorter.
  381. arr[0] = "Hi!" # Replacing value 1 with "Hi!".
  382. arr.append(4) # Array is now ["Hi!", 2, 3, 4].
  383. GDScript arrays are allocated linearly in memory for speed.
  384. Large arrays (more than tens of thousands of elements) may however cause
  385. memory fragmentation. If this is a concern, special types of
  386. arrays are available. These only accept a single data type. They avoid memory
  387. fragmentation and use less memory, but are atomic and tend to run slower than generic
  388. arrays. They are therefore only recommended to use for large data sets:
  389. - :ref:`PackedByteArray <class_PackedByteArray>`: An array of bytes (integers from 0 to 255).
  390. - :ref:`PackedInt32Array <class_PackedInt32Array>`: An array of 32-bit integers.
  391. - :ref:`PackedInt64Array <class_PackedInt64Array>`: An array of 64-bit integers.
  392. - :ref:`PackedFloat32Array <class_PackedFloat32Array>`: An array of 32-bit floats.
  393. - :ref:`PackedFloat64Array <class_PackedFloat64Array>`: An array of 64-bit floats.
  394. - :ref:`PackedStringArray <class_PackedStringArray>`: An array of strings.
  395. - :ref:`PackedVector2Array <class_PackedVector2Array>`: An array of :ref:`Vector2 <class_Vector2>` objects.
  396. - :ref:`PackedVector3Array <class_PackedVector3Array>`: An array of :ref:`Vector3 <class_Vector3>` objects.
  397. - :ref:`PackedColorArray <class_PackedColorArray>`: An array of :ref:`Color <class_Color>` objects.
  398. :ref:`Dictionary <class_Dictionary>`
  399. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  400. Associative container which contains values referenced by unique keys.
  401. ::
  402. var d = {4: 5, "A key": "A value", 28: [1, 2, 3]}
  403. d["Hi!"] = 0
  404. d = {
  405. 22: "value",
  406. "some_key": 2,
  407. "other_key": [2, 3, 4],
  408. "more_key": "Hello"
  409. }
  410. Lua-style table syntax is also supported. Lua-style uses ``=`` instead of ``:``
  411. and doesn't use quotes to mark string keys (making for slightly less to write).
  412. However, keys written in this form can't start with a digit (like any GDScript
  413. identifier).
  414. ::
  415. var d = {
  416. test22 = "value",
  417. some_key = 2,
  418. other_key = [2, 3, 4],
  419. more_key = "Hello"
  420. }
  421. To add a key to an existing dictionary, access it like an existing key and
  422. assign to it::
  423. var d = {} # Create an empty Dictionary.
  424. d.waiting = 14 # Add String "waiting" as a key and assign the value 14 to it.
  425. d[4] = "hello" # Add integer 4 as a key and assign the String "hello" as its value.
  426. d["Godot"] = 3.01 # Add String "Godot" as a key and assign the value 3.01 to it.
  427. var test = 4
  428. # Prints "hello" by indexing the dictionary with a dynamic key.
  429. # This is not the same as `d.test`. The bracket syntax equivalent to
  430. # `d.test` is `d["test"]`.
  431. print(d[test])
  432. .. note::
  433. The bracket syntax can be used to access properties of any
  434. :ref:`class_Object`, not just Dictionaries. Keep in mind it will cause a
  435. script error when attempting to index a non-existing property. To avoid
  436. this, use the :ref:`Object.get() <class_Object_method_get>` and
  437. :ref:`Object.set() <class_Object_method_set>` methods instead.
  438. Data
  439. ----
  440. Variables
  441. ~~~~~~~~~
  442. Variables can exist as class members or local to functions. They are
  443. created with the ``var`` keyword and may, optionally, be assigned a
  444. value upon initialization.
  445. ::
  446. var a # Data type is 'null' by default.
  447. var b = 5
  448. var c = 3.8
  449. var d = b + c # Variables are always initialized in order.
  450. Variables can optionally have a type specification. When a type is specified,
  451. the variable will be forced to have always that same type, and trying to assign
  452. an incompatible value will raise an error.
  453. Types are specified in the variable declaration using a ``:`` (colon) symbol
  454. after the variable name, followed by the type.
  455. ::
  456. var my_vector2: Vector2
  457. var my_node: Node = Sprite.new()
  458. If the variable is initialized within the declaration, the type can be inferred, so
  459. it's possible to omit the type name::
  460. var my_vector2 := Vector2() # 'my_vector2' is of type 'Vector2'.
  461. var my_node := Sprite.new() # 'my_node' is of type 'Sprite'.
  462. Type inference is only possible if the assigned value has a defined type, otherwise
  463. it will raise an error.
  464. Valid types are:
  465. - Built-in types (Array, Vector2, int, String, etc.).
  466. - Engine classes (Node, Resource, Reference, etc.).
  467. - Constant names if they contain a script resource (``MyScript`` if you declared ``const MyScript = preload("res://my_script.gd")``).
  468. - Other classes in the same script, respecting scope (``InnerClass.NestedClass`` if you declared ``class NestedClass`` inside the ``class InnerClass`` in the same scope).
  469. - Script classes declared with the ``class_name`` keyword.
  470. Casting
  471. ^^^^^^^
  472. Values assigned to typed variables must have a compatible type. If it's needed to
  473. coerce a value to be of a certain type, in particular for object types, you can
  474. use the casting operator ``as``.
  475. Casting between object types results in the same object if the value is of the
  476. same type or a subtype of the cast type.
  477. ::
  478. var my_node2D: Node2D
  479. my_node2D = $Sprite as Node2D # Works since Sprite is a subtype of Node2D.
  480. If the value is not a subtype, the casting operation will result in a ``null`` value.
  481. ::
  482. var my_node2D: Node2D
  483. my_node2D = $Button as Node2D # Results in 'null' since a Button is not a subtype of Node2D.
  484. For built-in types, they will be forcibly converted if possible, otherwise the
  485. engine will raise an error.
  486. ::
  487. var my_int: int
  488. my_int = "123" as int # The string can be converted to int.
  489. my_int = Vector2() as int # A Vector2 can't be converted to int, this will cause an error.
  490. Casting is also useful to have better type-safe variables when interacting with
  491. the scene tree::
  492. # Will infer the variable to be of type Sprite.
  493. var my_sprite := $Character as Sprite
  494. # Will fail if $AnimPlayer is not an AnimationPlayer, even if it has the method 'play()'.
  495. ($AnimPlayer as AnimationPlayer).play("walk")
  496. Constants
  497. ~~~~~~~~~
  498. Constants are similar to variables, but must be constants or constant
  499. expressions and must be assigned on initialization.
  500. ::
  501. const A = 5
  502. const B = Vector2(20, 20)
  503. const C = 10 + 20 # Constant expression.
  504. const D = Vector2(20, 30).x # Constant expression: 20.
  505. const E = [1, 2, 3, 4][0] # Constant expression: 1.
  506. const F = sin(20) # 'sin()' can be used in constant expressions.
  507. const G = x + 20 # Invalid; this is not a constant expression!
  508. const H = A + 20 # Constant expression: 25 (`A` is a constant).
  509. Although the type of constants is inferred from the assigned value, it's also
  510. possible to add explicit type specification::
  511. const A: int = 5
  512. const B: Vector2 = Vector2()
  513. Assigning a value of an incompatible type will raise an error.
  514. .. note::
  515. Since arrays and dictionaries are passed by reference, constants are "flat".
  516. This means that if you declare a constant array or dictionary, it can still
  517. be modified afterwards. They can't be reassigned with another value though.
  518. Enums
  519. ^^^^^
  520. Enums are basically a shorthand for constants, and are pretty useful if you
  521. want to assign consecutive integers to some constant.
  522. If you pass a name to the enum, it will put all the keys inside a constant
  523. dictionary of that name.
  524. .. important:: In Godot 3.1 and later, keys in a named enum are not registered
  525. as global constants. They should be accessed prefixed by the
  526. enum's name (``Name.KEY``); see an example below.
  527. ::
  528. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  529. # Is the same as:
  530. const TILE_BRICK = 0
  531. const TILE_FLOOR = 1
  532. const TILE_SPIKE = 2
  533. const TILE_TELEPORT = 3
  534. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  535. # Is the same as:
  536. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  537. # Access values with State.STATE_IDLE, etc.
  538. Functions
  539. ~~~~~~~~~
  540. Functions always belong to a `class <Classes_>`_. The scope priority for
  541. variable look-up is: local → class member → global. The ``self`` variable is
  542. always available and is provided as an option for accessing class members, but
  543. is not always required (and should *not* be sent as the function's first
  544. argument, unlike Python).
  545. ::
  546. func my_function(a, b):
  547. print(a)
  548. print(b)
  549. return a + b # Return is optional; without it 'null' is returned.
  550. A function can ``return`` at any point. The default return value is ``null``.
  551. Functions can also have type specification for the arguments and for the return
  552. value. Types for arguments can be added in a similar way to variables::
  553. func my_function(a: int, b: String):
  554. pass
  555. If a function argument has a default value, it's possible to infer the type::
  556. func my_function(int_arg := 42, String_arg := "string"):
  557. pass
  558. The return type of the function can be specified after the arguments list using
  559. the arrow token (``->``)::
  560. func my_int_function() -> int:
  561. return 0
  562. Functions that have a return type **must** return a proper value. Setting the
  563. type as ``void`` means the function doesn't return anything. Void functions can
  564. return early with the ``return`` keyword, but they can't return any value.
  565. ::
  566. void_function() -> void:
  567. return # Can't return a value
  568. .. note:: Non-void functions must **always** return a value, so if your code has
  569. branching statements (such as an ``if``/``else`` construct), all the
  570. possible paths must have a return. E.g., if you have a ``return``
  571. inside an ``if`` block but not after it, the editor will raise an
  572. error because if the block is not executed, the function won't have a
  573. valid value to return.
  574. Referencing functions
  575. ^^^^^^^^^^^^^^^^^^^^^
  576. Contrary to Python, functions are *not* first-class objects in GDScript. This
  577. means they cannot be stored in variables, passed as an argument to another
  578. function or be returned from other functions. This is for performance reasons.
  579. To reference a function by name at run-time, (e.g. to store it in a variable, or
  580. pass it to another function as an argument) one must use the ``call`` or
  581. ``funcref`` helpers::
  582. # Call a function by name in one step.
  583. my_node.call("my_function", args)
  584. # Store a function reference.
  585. var my_func = funcref(my_node, "my_function")
  586. # Call stored function reference.
  587. my_func.call_func(args)
  588. Static functions
  589. ^^^^^^^^^^^^^^^^
  590. A function can be declared static. When a function is static, it has no
  591. access to the instance member variables or ``self``. This is mainly
  592. useful to make libraries of helper functions::
  593. static func sum2(a, b):
  594. return a + b
  595. Statements and control flow
  596. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  597. Statements are standard and can be assignments, function calls, control
  598. flow structures, etc (see below). ``;`` as a statement separator is
  599. entirely optional.
  600. if/else/elif
  601. ^^^^^^^^^^^^
  602. Simple conditions are created by using the ``if``/``else``/``elif`` syntax.
  603. Parenthesis around conditions are allowed, but not required. Given the
  604. nature of the tab-based indentation, ``elif`` can be used instead of
  605. ``else``/``if`` to maintain a level of indentation.
  606. ::
  607. if [expression]:
  608. statement(s)
  609. elif [expression]:
  610. statement(s)
  611. else:
  612. statement(s)
  613. Short statements can be written on the same line as the condition::
  614. if 1 + 1 == 2: return 2 + 2
  615. else:
  616. var x = 3 + 3
  617. return x
  618. Sometimes, you might want to assign a different initial value based on a
  619. boolean expression. In this case, ternary-if expressions come in handy::
  620. var x = [value] if [expression] else [value]
  621. y += 3 if y < 10 else -1
  622. while
  623. ^^^^^
  624. Simple loops are created by using ``while`` syntax. Loops can be broken
  625. using ``break`` or continued using ``continue``:
  626. ::
  627. while [expression]:
  628. statement(s)
  629. for
  630. ^^^
  631. To iterate through a range, such as an array or table, a *for* loop is
  632. used. When iterating over an array, the current array element is stored in
  633. the loop variable. When iterating over a dictionary, the *key* is stored
  634. in the loop variable.
  635. ::
  636. for x in [5, 7, 11]:
  637. statement # Loop iterates 3 times with 'x' as 5, then 7 and finally 11.
  638. var dict = {"a": 0, "b": 1, "c": 2}
  639. for i in dict:
  640. print(dict[i]) # Prints 0, then 1, then 2.
  641. for i in range(3):
  642. statement # Similar to [0, 1, 2] but does not allocate an array.
  643. for i in range(1, 3):
  644. statement # Similar to [1, 2] but does not allocate an array.
  645. for i in range(2, 8, 2):
  646. statement # Similar to [2, 4, 6] but does not allocate an array.
  647. for c in "Hello":
  648. print(c) # Iterate through all characters in a String, print every letter on new line.
  649. for i in 3:
  650. statement # Similar to range(3)
  651. for i in 2.2:
  652. statement # Similar to range(ceil(2.2))
  653. match
  654. ^^^^^
  655. A ``match`` statement is used to branch execution of a program.
  656. It's the equivalent of the ``switch`` statement found in many other languages, but offers some additional features.
  657. Basic syntax::
  658. match [expression]:
  659. [pattern](s):
  660. [block]
  661. [pattern](s):
  662. [block]
  663. [pattern](s):
  664. [block]
  665. **Crash-course for people who are familiar with switch statements**:
  666. 1. Replace ``switch`` with ``match``.
  667. 2. Remove ``case``.
  668. 3. Remove any ``break``\ s. If you don't want to ``break`` by default, you can use ``continue`` for a fallthrough.
  669. 4. Change ``default`` to a single underscore.
  670. **Control flow**:
  671. The patterns are matched from top to bottom.
  672. If a pattern matches, the first corresponding block will be executed. After that, the execution continues below the ``match`` statement.
  673. You can use ``continue`` to stop execution in the current block and check for an additional match in the patterns below it.
  674. There are 6 pattern types:
  675. - Constant pattern
  676. Constant primitives, like numbers and strings::
  677. match x:
  678. 1:
  679. print("We are number one!")
  680. 2:
  681. print("Two are better than one!")
  682. "test":
  683. print("Oh snap! It's a string!")
  684. - Variable pattern
  685. Matches the contents of a variable/enum::
  686. match typeof(x):
  687. TYPE_REAL:
  688. print("float")
  689. TYPE_STRING:
  690. print("text")
  691. TYPE_ARRAY:
  692. print("array")
  693. - Wildcard pattern
  694. This pattern matches everything. It's written as a single underscore.
  695. It can be used as the equivalent of the ``default`` in a ``switch`` statement in other languages::
  696. match x:
  697. 1:
  698. print("It's one!")
  699. 2:
  700. print("It's one times two!")
  701. _:
  702. print("It's not 1 or 2. I don't care to be honest.")
  703. - Binding pattern
  704. A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name.
  705. It's especially useful in array and dictionary patterns::
  706. match x:
  707. 1:
  708. print("It's one!")
  709. 2:
  710. print("It's one times two!")
  711. var new_var:
  712. print("It's not 1 or 2, it's ", new_var)
  713. - Array pattern
  714. Matches an array. Every single element of the array pattern is a pattern itself, so you can nest them.
  715. The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  716. **Open-ended array**: An array can be bigger than the pattern by making the last subpattern ``..``.
  717. Every subpattern has to be comma-separated.
  718. ::
  719. match x:
  720. []:
  721. print("Empty array")
  722. [1, 3, "test", null]:
  723. print("Very specific array")
  724. [var start, _, "test"]:
  725. print("First element is ", start, ", and the last is \"test\"")
  726. [42, ..]:
  727. print("Open ended array")
  728. - Dictionary pattern
  729. Works in the same way as the array pattern. Every key has to be a constant pattern.
  730. The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  731. **Open-ended dictionary**: A dictionary can be bigger than the pattern by making the last subpattern ``..``.
  732. Every subpattern has to be comma separated.
  733. If you don't specify a value, then only the existence of the key is checked.
  734. A value pattern is separated from the key pattern with a ``:``.
  735. ::
  736. match x:
  737. {}:
  738. print("Empty dict")
  739. {"name": "Dennis"}:
  740. print("The name is Dennis")
  741. {"name": "Dennis", "age": var age}:
  742. print("Dennis is ", age, " years old.")
  743. {"name", "age"}:
  744. print("Has a name and an age, but it's not Dennis :(")
  745. {"key": "godotisawesome", ..}:
  746. print("I only checked for one entry and ignored the rest")
  747. - Multiple patterns
  748. You can also specify multiple patterns separated by a comma. These patterns aren't allowed to have any bindings in them.
  749. ::
  750. match x:
  751. 1, 2, 3:
  752. print("It's 1 - 3")
  753. "Sword", "Splash potion", "Fist":
  754. print("Yep, you've taken damage")
  755. Classes
  756. ~~~~~~~
  757. By default, all script files are unnamed classes. In this case, you can only
  758. reference them using the file's path, using either a relative or an absolute
  759. path. For example, if you name a script file ``character.gd``::
  760. # Inherit from 'Character.gd'.
  761. extends "res://path/to/character.gd"
  762. # Load character.gd and create a new node instance from it.
  763. var Character = load("res://path/to/character.gd")
  764. var character_node = Character.new()
  765. Instead, you can give your class a name to register it as a new type in Godot's
  766. editor. For that, you use the ``class_name`` keyword. You can add an
  767. optional comma followed by a path to an image, to use it as an icon. Your class
  768. will then appear with its new icon in the editor::
  769. # Item.gd
  770. extends Node
  771. class_name Item, "res://interface/icons/item.png"
  772. .. image:: img/class_name_editor_register_example.png
  773. Here's a class file example:
  774. ::
  775. # Saved as a file named 'character.gd'.
  776. class_name Character
  777. var health = 5
  778. func print_health():
  779. print(health)
  780. func print_this_script_three_times():
  781. print(get_script())
  782. print(ResourceLoader.load("res://character.gd"))
  783. print(Character)
  784. .. note:: Godot's class syntax is compact: it can only contain member variables or
  785. functions. You can use static functions, but not static member variables. In the
  786. same way, the engine initializes variables every time you create an instance,
  787. and this includes arrays and dictionaries. This is in the spirit of thread
  788. safety, since scripts can be initialized in separate threads without the user
  789. knowing.
  790. Inheritance
  791. ^^^^^^^^^^^
  792. A class (stored as a file) can inherit from:
  793. - A global class.
  794. - Another class file.
  795. - An inner class inside another class file.
  796. Multiple inheritance is not allowed.
  797. Inheritance uses the ``extends`` keyword::
  798. # Inherit/extend a globally available class.
  799. extends SomeClass
  800. # Inherit/extend a named class file.
  801. extends "somefile.gd"
  802. # Inherit/extend an inner class in another file.
  803. extends "somefile.gd".SomeInnerClass
  804. To check if a given instance inherits from a given class,
  805. the ``is`` keyword can be used::
  806. # Cache the enemy class.
  807. const Enemy = preload("enemy.gd")
  808. # [...]
  809. # Use 'is' to check inheritance.
  810. if entity is Enemy:
  811. entity.apply_damage()
  812. To call a function in a *parent class* (i.e. one ``extend``-ed in your current
  813. class), prepend ``.`` to the function name::
  814. .base_func(args)
  815. This is especially useful because functions in extending classes replace
  816. functions with the same name in their parent classes. If you still want to
  817. call them, you can prefix them with ``.`` (like the ``super`` keyword
  818. in other languages)::
  819. func some_func(x):
  820. .some_func(x) # Calls the same function on the parent class.
  821. .. note:: Default functions like ``_init``, and most notifications such as
  822. ``_enter_tree``, ``_exit_tree``, ``_process``, ``_physics_process``,
  823. etc. are called in all parent classes automatically.
  824. There is no need to call them explicitly when overloading them.
  825. Class Constructor
  826. ^^^^^^^^^^^^^^^^^
  827. The class constructor, called on class instantiation, is named ``_init``. As
  828. mentioned earlier, the constructors of parent classes are called automatically
  829. when inheriting a class. So, there is usually no need to call ``._init()``
  830. explicitly.
  831. Unlike the call of a regular function, like in the above example with
  832. ``.some_func``, if the constructor from the inherited class takes arguments,
  833. they are passed like this::
  834. func _init(args).(parent_args):
  835. pass
  836. This is better explained through examples. Consider this scenario::
  837. # State.gd (inherited class)
  838. var entity = null
  839. var message = null
  840. func _init(e=null):
  841. entity = e
  842. func enter(m):
  843. message = m
  844. # Idle.gd (inheriting class)
  845. extends "State.gd"
  846. func _init(e=null, m=null).(e):
  847. # Do something with 'e'.
  848. message = m
  849. There are a few things to keep in mind here:
  850. 1. If the inherited class (``State.gd``) defines a ``_init`` constructor that takes
  851. arguments (``e`` in this case), then the inheriting class (``Idle.gd``) *must*
  852. define ``_init`` as well and pass appropriate parameters to ``_init`` from ``State.gd``.
  853. 2. ``Idle.gd`` can have a different number of arguments than the parent class ``State.gd``.
  854. 3. In the example above, ``e`` passed to the ``State.gd`` constructor is the same ``e`` passed
  855. in to ``Idle.gd``.
  856. 4. If ``Idle.gd``'s ``_init`` constructor takes 0 arguments, it still needs to pass some value
  857. to the ``State.gd`` parent class, even if it does nothing. This brings us to the fact that you
  858. can pass literals in the base constructor as well, not just variables. eg.::
  859. # Idle.gd
  860. func _init().(5):
  861. pass
  862. Inner classes
  863. ^^^^^^^^^^^^^
  864. A class file can contain inner classes. Inner classes are defined using the
  865. ``class`` keyword. They are instanced using the ``ClassName.new()``
  866. function.
  867. ::
  868. # Inside a class file.
  869. # An inner class in this class file.
  870. class SomeInnerClass:
  871. var a = 5
  872. func print_value_of_a():
  873. print(a)
  874. # This is the constructor of the class file's main class.
  875. func _init():
  876. var c = SomeInnerClass.new()
  877. c.print_value_of_a()
  878. .. _doc_gdscript_classes_as_resources:
  879. Classes as resources
  880. ^^^^^^^^^^^^^^^^^^^^
  881. Classes stored as files are treated as :ref:`resources <class_GDScript>`. They
  882. must be loaded from disk to access them in other classes. This is done using
  883. either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
  884. class resource is done by calling the ``new`` function on the class object::
  885. # Load the class resource when calling load().
  886. var my_class = load("myclass.gd")
  887. # Preload the class only once at compile time.
  888. const MyClass = preload("myclass.gd")
  889. func _init():
  890. var a = MyClass.new()
  891. a.some_function()
  892. Exports
  893. ~~~~~~~
  894. .. note::
  895. Documentation about exports has been moved to :ref:`doc_gdscript_exports`.
  896. Setters/getters
  897. ~~~~~~~~~~~~~~~
  898. It is often useful to know when a class' member variable changes for
  899. whatever reason. It may also be desired to encapsulate its access in some way.
  900. For this, GDScript provides a *setter/getter* syntax using the ``setget`` keyword.
  901. It is used directly after a variable definition:
  902. ::
  903. var variable = value setget setterfunc, getterfunc
  904. Whenever the value of ``variable`` is modified by an *external* source
  905. (i.e. not from local usage in the class), the *setter* function (``setterfunc`` above)
  906. will be called. This happens *before* the value is changed. The *setter* must decide what to do
  907. with the new value. Vice versa, when ``variable`` is accessed, the *getter* function
  908. (``getterfunc`` above) must ``return`` the desired value. Below is an example::
  909. var my_var setget my_var_set, my_var_get
  910. func my_var_set(new_value):
  911. my_var = new_value
  912. func my_var_get():
  913. return my_var # Getter must return a value.
  914. Either of the *setter* or *getter* functions can be omitted::
  915. # Only a setter.
  916. var my_var = 5 setget my_var_set
  917. # Only a getter (note the comma).
  918. var my_var = 5 setget ,my_var_get
  919. Setters and getters are useful when :ref:`exporting variables <doc_gdscript_exports>`
  920. to the editor in tool scripts or plugins, for validating input.
  921. As said, *local* access will *not* trigger the setter and getter. Here is an
  922. illustration of this:
  923. ::
  924. func _init():
  925. # Does not trigger setter/getter.
  926. my_integer = 5
  927. print(my_integer)
  928. # Does trigger setter/getter.
  929. self.my_integer = 5
  930. print(self.my_integer)
  931. .. _doc_gdscript_tool_mode:
  932. Tool mode
  933. ~~~~~~~~~
  934. By default, scripts don't run inside the editor and only the exported
  935. properties can be changed. In some cases, it is desired that they do run
  936. inside the editor (as long as they don't execute game code or manually
  937. avoid doing so). For this, the ``tool`` keyword exists and must be
  938. placed at the top of the file::
  939. tool
  940. extends Button
  941. func _ready():
  942. print("Hello")
  943. See :ref:`doc_running_code_in_the_editor` for more information.
  944. .. warning:: Be cautious when freeing nodes with ``queue_free()`` or ``free()``
  945. in a tool script (especially the script's owner itself). As tool
  946. scripts run their code in the editor, misusing them may lead to
  947. crashing the editor.
  948. Memory management
  949. ~~~~~~~~~~~~~~~~~
  950. If a class inherits from :ref:`class_Reference`, then instances will be
  951. freed when no longer in use. No garbage collector exists, just
  952. reference counting. By default, all classes that don't define
  953. inheritance extend **Reference**. If this is not desired, then a class
  954. must inherit :ref:`class_Object` manually and must call ``instance.free()``. To
  955. avoid reference cycles that can't be freed, a ``weakref`` function is
  956. provided for creating weak references.
  957. Alternatively, when not using references, the
  958. ``is_instance_valid(instance)`` can be used to check if an object has been
  959. freed.
  960. .. _doc_gdscript_signals:
  961. Signals
  962. ~~~~~~~
  963. Signals are a tool to emit messages from an object that other objects can react
  964. to. To create custom signals for a class, use the ``signal`` keyword.
  965. ::
  966. extends Node
  967. # A signal named health_depleted.
  968. signal health_depleted
  969. .. note::
  970. Signals are a `Callback
  971. <https://en.wikipedia.org/wiki/Callback_(computer_programming)>`_
  972. mechanism. They also fill the role of Observers, a common programming
  973. pattern. For more information, read the `Observer tutorial
  974. <https://gameprogrammingpatterns.com/observer.html>`_ in the
  975. Game Programming Patterns ebook.
  976. You can connect these signals to methods the same way you connect built-in
  977. signals of nodes like :ref:`class_Button` or :ref:`class_RigidBody`.
  978. In the example below, we connect the ``health_depleted`` signal from a
  979. ``Character`` node to a ``Game`` node. When the ``Character`` node emits the
  980. signal, the game node's ``_on_Character_health_depleted`` is called::
  981. # Game.gd
  982. func _ready():
  983. var character_node = get_node('Character')
  984. character_node.connect("health_depleted", self, "_on_Character_health_depleted")
  985. func _on_Character_health_depleted():
  986. get_tree().reload_current_scene()
  987. You can emit as many arguments as you want along with a signal.
  988. Here is an example where this is useful. Let's say we want a life bar on screen
  989. to react to health changes with an animation, but we want to keep the user
  990. interface separate from the player in our scene tree.
  991. In our ``Character.gd`` script, we define a ``health_changed`` signal and emit
  992. it with :ref:`Object.emit_signal() <class_Object_method_emit_signal>`, and from
  993. a ``Game`` node higher up our scene tree, we connect it to the ``Lifebar`` using
  994. the :ref:`Object.connect() <class_Object_method_connect>` method::
  995. # Character.gd
  996. ...
  997. signal health_changed
  998. func take_damage(amount):
  999. var old_health = health
  1000. health -= amount
  1001. # We emit the health_changed signal every time the
  1002. # character takes damage.
  1003. emit_signal("health_changed", old_health, health)
  1004. ...
  1005. ::
  1006. # Lifebar.gd
  1007. # Here, we define a function to use as a callback when the
  1008. # character's health_changed signal is emitted.
  1009. ...
  1010. func _on_Character_health_changed(old_value, new_value):
  1011. if old_value > new_value:
  1012. progress_bar.modulate = Color.red
  1013. else:
  1014. progress_bar.modulate = Color.green
  1015. # Imagine that `animate` is a user-defined function that animates the
  1016. # bar filling up or emptying itself.
  1017. progress_bar.animate(old_value, new_value)
  1018. ...
  1019. .. note::
  1020. To use signals, your class has to extend the ``Object`` class or any
  1021. type extending it like ``Node``, ``KinematicBody``, ``Control``...
  1022. In the ``Game`` node, we get both the ``Character`` and ``Lifebar`` nodes, then
  1023. connect the character, that emits the signal, to the receiver, the ``Lifebar``
  1024. node in this case.
  1025. ::
  1026. # Game.gd
  1027. func _ready():
  1028. var character_node = get_node('Character')
  1029. var lifebar_node = get_node('UserInterface/Lifebar')
  1030. character_node.connect("health_changed", lifebar_node, "_on_Character_health_changed")
  1031. This allows the ``Lifebar`` to react to health changes without coupling it to
  1032. the ``Character`` node.
  1033. You can write optional argument names in parentheses after the signal's
  1034. definition::
  1035. # Defining a signal that forwards two arguments.
  1036. signal health_changed(old_value, new_value)
  1037. These arguments show up in the editor's node dock, and Godot can use them to
  1038. generate callback functions for you. However, you can still emit any number of
  1039. arguments when you emit signals; it's up to you to emit the correct values.
  1040. .. image:: img/gdscript_basics_signals_node_tab_1.png
  1041. GDScript can bind an array of values to connections between a signal
  1042. and a method. When the signal is emitted, the callback method receives
  1043. the bound values. These bound arguments are unique to each connection,
  1044. and the values will stay the same.
  1045. You can use this array of values to add extra constant information to the
  1046. connection if the emitted signal itself doesn't give you access to all the data
  1047. that you need.
  1048. Building on the example above, let's say we want to display a log of the damage
  1049. taken by each character on the screen, like ``Player1 took 22 damage.``. The
  1050. ``health_changed`` signal doesn't give us the name of the character that took
  1051. damage. So when we connect the signal to the in-game console, we can add the
  1052. character's name in the binds array argument::
  1053. # Game.gd
  1054. func _ready():
  1055. var character_node = get_node('Character')
  1056. var battle_log_node = get_node('UserInterface/BattleLog')
  1057. character_node.connect("health_changed", battle_log_node, "_on_Character_health_changed", [character_node.name])
  1058. Our ``BattleLog`` node receives each element in the binds array as an extra argument::
  1059. # BattleLog.gd
  1060. func _on_Character_health_changed(old_value, new_value, character_name):
  1061. if not new_value <= old_value:
  1062. return
  1063. var damage = old_value - new_value
  1064. label.text += character_name + " took " + str(damage) + " damage."
  1065. Coroutines with yield
  1066. ~~~~~~~~~~~~~~~~~~~~~
  1067. GDScript offers support for `coroutines <https://en.wikipedia.org/wiki/Coroutine>`_
  1068. via the :ref:`yield<class_@GDScript_method_yield>` built-in function. Calling ``yield()`` will
  1069. immediately return from the current function, with the current frozen
  1070. state of the same function as the return value. Calling ``resume()`` on
  1071. this resulting object will continue execution and return whatever the
  1072. function returns. Once resumed, the state object becomes invalid. Here is
  1073. an example::
  1074. func my_func():
  1075. print("Hello")
  1076. yield()
  1077. print("world")
  1078. func _ready():
  1079. var y = my_func()
  1080. # Function state saved in 'y'.
  1081. print("my dear")
  1082. y.resume()
  1083. # 'y' resumed and is now an invalid state.
  1084. Will print::
  1085. Hello
  1086. my dear
  1087. world
  1088. It is also possible to pass values between ``yield()`` and ``resume()``,
  1089. for example::
  1090. func my_func():
  1091. print("Hello")
  1092. print(yield())
  1093. return "cheers!"
  1094. func _ready():
  1095. var y = my_func()
  1096. # Function state saved in 'y'.
  1097. print(y.resume("world"))
  1098. # 'y' resumed and is now an invalid state.
  1099. Will print::
  1100. Hello
  1101. world
  1102. cheers!
  1103. Remember to save the new function state, when using multiple ``yield``\s::
  1104. func co_func():
  1105. for i in range(1, 5):
  1106. print("Turn %d" % i)
  1107. yield();
  1108. func _ready():
  1109. var co = co_func();
  1110. while co is GDScriptFunctionState && co.is_valid():
  1111. co = co.resume();
  1112. Coroutines & signals
  1113. ^^^^^^^^^^^^^^^^^^^^
  1114. The real strength of using ``yield`` is when combined with signals.
  1115. ``yield`` can accept two arguments, an object and a signal. When the
  1116. signal is received, execution will recommence. Here are some examples::
  1117. # Resume execution the next frame.
  1118. yield(get_tree(), "idle_frame")
  1119. # Resume execution when animation is done playing.
  1120. yield(get_node("AnimationPlayer"), "animation_finished")
  1121. # Wait 5 seconds, then resume execution.
  1122. yield(get_tree().create_timer(5.0), "timeout")
  1123. Coroutines themselves use the ``completed`` signal when they transition
  1124. into an invalid state, for example::
  1125. func my_func():
  1126. yield(button_func(), "completed")
  1127. print("All buttons were pressed, hurray!")
  1128. func button_func():
  1129. yield($Button0, "pressed")
  1130. yield($Button1, "pressed")
  1131. ``my_func`` will only continue execution once both buttons have been pressed.
  1132. You can also get the signal's argument once it's emitted by an object:
  1133. ::
  1134. # Wait for when any node is added to the scene tree.
  1135. var node = yield(get_tree(), "node_added")
  1136. If you're unsure whether a function may yield or not, or whether it may yield
  1137. multiple times, you can yield to the ``completed`` signal conditionally:
  1138. ::
  1139. func generate():
  1140. var result = rand_range(-1.0, 1.0)
  1141. if result < 0.0:
  1142. yield(get_tree(), "idle_frame")
  1143. return result
  1144. func make():
  1145. var result = generate()
  1146. if result is GDScriptFunctionState: # Still working.
  1147. result = yield(result, "completed")
  1148. return result
  1149. This ensures that the function returns whatever it was supposed to return
  1150. regardless of whether coroutines were used internally. Note that using
  1151. ``while`` would be redundant here as the ``completed`` signal is only emitted
  1152. when the function didn't yield anymore.
  1153. Onready keyword
  1154. ~~~~~~~~~~~~~~~
  1155. When using nodes, it's common to desire to keep references to parts
  1156. of the scene in a variable. As scenes are only warranted to be
  1157. configured when entering the active scene tree, the sub-nodes can only
  1158. be obtained when a call to ``Node._ready()`` is made.
  1159. ::
  1160. var my_label
  1161. func _ready():
  1162. my_label = get_node("MyLabel")
  1163. This can get a little cumbersome, especially when nodes and external
  1164. references pile up. For this, GDScript has the ``onready`` keyword, that
  1165. defers initialization of a member variable until ``_ready()`` is called. It
  1166. can replace the above code with a single line::
  1167. onready var my_label = get_node("MyLabel")
  1168. Assert keyword
  1169. ~~~~~~~~~~~~~~
  1170. The ``assert`` keyword can be used to check conditions in debug builds. These
  1171. assertions are ignored in non-debug builds. This means that the expression
  1172. passed as argument won't be evaluated in a project exported in release mode.
  1173. Due to this, assertions must **not** contain expressions that have
  1174. side effects. Otherwise, the behavior of the script would vary
  1175. depending on whether the project is run in a debug build.
  1176. ::
  1177. # Check that 'i' is 0. If 'i' is not 0, an assertion error will occur.
  1178. assert(i == 0)
  1179. When running a project from the editor, the project will be paused if an
  1180. assertion error occurs.