gdscript_basics.rst 61 KB

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