gdscript_basics.rst 66 KB

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