gdscript_basics.rst 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  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. |
  132. +------------+---------------------------------------------------------------------------------------------------------------+
  133. | case | Reserved for future implementation. |
  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 would also put all the values inside a
  507. constant dictionary of that name.
  508. ::
  509. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  510. # Is the same as:
  511. const TILE_BRICK = 0
  512. const TILE_FLOOR = 1
  513. const TILE_SPIKE = 2
  514. const TILE_TELEPORT = 3
  515. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  516. # Is the same as:
  517. const STATE_IDLE = 0
  518. const STATE_JUMP = 5
  519. const STATE_SHOOT = 6
  520. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  521. Functions
  522. ~~~~~~~~~
  523. Functions always belong to a `class <Classes_>`_. The scope priority for
  524. variable look-up is: local → class member → global. The ``self`` variable is
  525. always available and is provided as an option for accessing class members, but
  526. is not always required (and should *not* be sent as the function's first
  527. argument, unlike Python).
  528. ::
  529. func my_function(a, b):
  530. print(a)
  531. print(b)
  532. return a + b # Return is optional; without it 'null' is returned.
  533. A function can ``return`` at any point. The default return value is ``null``.
  534. Functions can also have type specification for the arguments and for the return
  535. value. Types for arguments can be added in a similar way to variables::
  536. func my_function(a: int, b: String):
  537. pass
  538. If a function argument has a default value, it's possible to infer the type::
  539. func my_function(int_arg := 42, String_arg := "string"):
  540. pass
  541. The return type of the function can be specified after the arguments list using
  542. the arrow token (``->``)::
  543. func my_int_function() -> int:
  544. return 0
  545. Functions that have a return type **must** return a proper value. Setting the
  546. type as ``void`` means the function doesn't return anything. Void functions can
  547. return early with the ``return`` keyword, but they can't return any value.
  548. ::
  549. void_function() -> void:
  550. return # Can't return a value
  551. .. note:: Non-void functions must **always** return a value, so if your code has
  552. branching statements (such as an ``if``/``else`` construct), all the
  553. possible paths must have a return. E.g., if you have a ``return``
  554. inside an ``if`` block but not after it, the editor will raise an
  555. error because if the block is not executed, the function won't have a
  556. valid value to return.
  557. Referencing Functions
  558. ^^^^^^^^^^^^^^^^^^^^^
  559. Contrary to Python, functions are *not* first class objects in GDScript. This
  560. means they cannot be stored in variables, passed as an argument to another
  561. function or be returned from other functions. This is for performance reasons.
  562. To reference a function by name at runtime, (e.g. to store it in a variable, or
  563. pass it to another function as an argument) one must use the ``call`` or
  564. ``funcref`` helpers::
  565. # Call a function by name in one step.
  566. my_node.call("my_function", args)
  567. # Store a function reference.
  568. var my_func = funcref(my_node, "my_function")
  569. # Call stored function reference.
  570. my_func.call_func(args)
  571. Remember that default functions, like ``_init``, and most
  572. notifications, such as ``_enter_tree``, ``_exit_tree``, ``_process``,
  573. ``_physics_process``, etc. are called in all base classes automatically.
  574. So there is only a need to call the function explicitly when overloading
  575. them in some way.
  576. Static functions
  577. ^^^^^^^^^^^^^^^^
  578. A function can be declared static. When a function is static, it has no
  579. access to the instance member variables or ``self``. This is mainly
  580. useful to make libraries of helper functions:
  581. ::
  582. static func sum2(a, b):
  583. return a + b
  584. Statements and control flow
  585. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  586. Statements are standard and can be assignments, function calls, control
  587. flow structures, etc (see below). ``;`` as a statement separator is
  588. entirely optional.
  589. if/else/elif
  590. ^^^^^^^^^^^^
  591. Simple conditions are created by using the ``if``/``else``/``elif`` syntax.
  592. Parenthesis around conditions are allowed, but not required. Given the
  593. nature of the tab-based indentation, ``elif`` can be used instead of
  594. ``else``/``if`` to maintain a level of indentation.
  595. ::
  596. if [expression]:
  597. statement(s)
  598. elif [expression]:
  599. statement(s)
  600. else:
  601. statement(s)
  602. Short statements can be written on the same line as the condition::
  603. if 1 + 1 == 2: return 2 + 2
  604. else:
  605. var x = 3 + 3
  606. return x
  607. Sometimes you might want to assign a different initial value based on a
  608. boolean expression. In this case, ternary-if expressions come in handy::
  609. var x = [value] if [expression] else [value]
  610. y += 3 if y < 10 else -1
  611. while
  612. ^^^^^
  613. Simple loops are created by using ``while`` syntax. Loops can be broken
  614. using ``break`` or continued using ``continue``:
  615. ::
  616. while [expression]:
  617. statement(s)
  618. for
  619. ^^^
  620. To iterate through a range, such as an array or table, a *for* loop is
  621. used. When iterating over an array, the current array element is stored in
  622. the loop variable. When iterating over a dictionary, the *index* is stored
  623. in the loop variable.
  624. ::
  625. for x in [5, 7, 11]:
  626. statement # Loop iterates 3 times with 'x' as 5, then 7 and finally 11.
  627. var dict = {"a": 0, "b": 1, "c": 2}
  628. for i in dict:
  629. print(dict[i])
  630. for i in range(3):
  631. statement # Similar to [0, 1, 2] but does not allocate an array.
  632. for i in range(1,3):
  633. statement # Similar to [1, 2] but does not allocate an array.
  634. for i in range(2,8,2):
  635. statement # Similar to [2, 4, 6] but does not allocate an array.
  636. for c in "Hello":
  637. print(c) # Iterate through all characters in a String, print every letter on new line.
  638. match
  639. ^^^^^
  640. A ``match`` statement is used to branch execution of a program.
  641. It's the equivalent of the ``switch`` statement found in many other languages, but offers some additional features.
  642. Basic syntax:
  643. ::
  644. match [expression]:
  645. [pattern](s):
  646. [block]
  647. [pattern](s):
  648. [block]
  649. [pattern](s):
  650. [block]
  651. **Crash-course for people who are familiar with switch statements**:
  652. 1. Replace ``switch`` with ``match``
  653. 2. Remove ``case``
  654. 3. Remove any ``break``\ s. If you don't want to ``break`` by default, you can use ``continue`` for a fallthrough.
  655. 4. Change ``default`` to a single underscore.
  656. **Control flow**:
  657. The patterns are matched from top to bottom.
  658. If a pattern matches, the corresponding block will be executed. After that, the execution continues below the ``match`` statement.
  659. If you want to have a fallthrough, you can use ``continue`` to stop execution in the current block and check the ones below it.
  660. There are 6 pattern types:
  661. - constant pattern
  662. constant primitives, like numbers and strings ::
  663. match x:
  664. 1:
  665. print("We are number one!")
  666. 2:
  667. print("Two are better than one!")
  668. "test":
  669. print("Oh snap! It's a string!")
  670. - variable pattern
  671. matches the contents of a variable/enum ::
  672. match typeof(x):
  673. TYPE_REAL:
  674. print("float")
  675. TYPE_STRING:
  676. print("text")
  677. TYPE_ARRAY:
  678. print("array")
  679. - wildcard pattern
  680. This pattern matches everything. It's written as a single underscore.
  681. It can be used as the equivalent of the ``default`` in a ``switch`` statement in other languages. ::
  682. match x:
  683. 1:
  684. print("It's one!")
  685. 2:
  686. print("It's one times two!")
  687. _:
  688. print("It's not 1 or 2. I don't care tbh.")
  689. - binding pattern
  690. A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name.
  691. It's especially useful in array and dictionary patterns. ::
  692. match x:
  693. 1:
  694. print("It's one!")
  695. 2:
  696. print("It's one times two!")
  697. var new_var:
  698. print("It's not 1 or 2, it's ", new_var)
  699. - array pattern
  700. matches an array. Every single element of the array pattern is a pattern itself, so you can nest them.
  701. The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  702. **Open-ended array**: An array can be bigger than the pattern by making the last subpattern ``..``
  703. Every subpattern has to be comma separated. ::
  704. match x:
  705. []:
  706. print("Empty array")
  707. [1, 3, "test", null]:
  708. print("Very specific array")
  709. [var start, _, "test"]:
  710. print("First element is ", start, ", and the last is \"test\"")
  711. [42, ..]:
  712. print("Open ended array")
  713. - dictionary pattern
  714. Works in the same way as the array pattern. Every key has to be a constant pattern.
  715. The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern doesn't match.
  716. **Open-ended dictionary**: A dictionary can be bigger than the pattern by making the last subpattern ``..``
  717. Every subpattern has to be comma separated.
  718. If you don't specify a value, then only the existence of the key is checked.
  719. A value pattern is separated from the key pattern with a ``:`` ::
  720. match x:
  721. {}:
  722. print("Empty dict")
  723. {"name": "Dennis"}:
  724. print("The name is Dennis")
  725. {"name": "Dennis", "age": var age}:
  726. print("Dennis is ", age, " years old.")
  727. {"name", "age"}:
  728. print("Has a name and an age, but it's not Dennis :(")
  729. {"key": "godotisawesome", ..}:
  730. print("I only checked for one entry and ignored the rest")
  731. Multipatterns:
  732. You can also specify multiple patterns separated by a comma. These patterns aren't allowed to have any bindings in them. ::
  733. match x:
  734. 1, 2, 3:
  735. print("It's 1 - 3")
  736. "Sword", "Splash potion", "Fist":
  737. print("Yep, you've taken damage")
  738. Classes
  739. ~~~~~~~
  740. By default, all script files are unnamed classes. In this case, you can only
  741. reference them using the file's path, using either a relative or an absolute
  742. path. For example, if you name a script file ``character.gd``
  743. ::
  744. # Inherit from Character.gd
  745. extends res://path/to/character.gd
  746. # Load character.gd and create a new node instance from it
  747. var Character = load("res://path/to/character.gd")
  748. var character_node = Character.new()
  749. Instead, you can give your class a name to register it as a new type in Godot's
  750. editor. For that, you use the 'class_name' keyword. You can add an
  751. optional comma followed by a path to an image, to use it as an icon. Your class
  752. will then appear with its new icon in the editor:
  753. ::
  754. # Item.gd
  755. extends Node
  756. class_name Item, "res://interface/icons/item.png"
  757. .. image:: img/class_name_editor_register_example.png
  758. Here's a class file example:
  759. ::
  760. # Saved as a file named 'character.gd'.
  761. class_name Character
  762. var health = 5
  763. func print_health():
  764. print(health)
  765. func print_this_script_three_times():
  766. print(get_script())
  767. print(ResourceLoader.load("res://character.gd"))
  768. print(Character)
  769. .. note:: Godot's class syntax is compact: it can only contain member variables or
  770. functions. You can use static functions, but not static member variables. In the
  771. same way, the engine initializes variables every time you create an instance,
  772. and this includes arrays and dictionaries. This is in the spirit of thread
  773. safety, since scripts can be initialized in separate threads without the user
  774. knowing.
  775. Inheritance
  776. ^^^^^^^^^^^
  777. A class (stored as a file) can inherit from
  778. - A global class
  779. - Another class file
  780. - An inner class inside another class file.
  781. Multiple inheritance is not allowed.
  782. Inheritance uses the ``extends`` keyword:
  783. ::
  784. # Inherit/extend a globally available class.
  785. extends SomeClass
  786. # Inherit/extend a named class file.
  787. extends "somefile.gd"
  788. # Inherit/extend an inner class in another file.
  789. extends "somefile.gd".SomeInnerClass
  790. To check if a given instance inherits from a given class,
  791. the ``is`` keyword can be used:
  792. ::
  793. # Cache the enemy class.
  794. const Enemy = preload("enemy.gd")
  795. # [...]
  796. # Use 'is' to check inheritance.
  797. if (entity is Enemy):
  798. entity.apply_damage()
  799. To call a function in a *base class* (i.e. one ``extend``-ed in your current class),
  800. prepend ``.`` to the function name:
  801. ::
  802. .basefunc(args)
  803. This is especially useful because functions in extending classes replace
  804. functions with the same name in their base classes. So if you still want
  805. to call them, you can use ``.`` like the ``super`` keyword in other languages:
  806. ::
  807. func some_func(x):
  808. .some_func(x) # Calls same function on the parent class.
  809. Class Constructor
  810. ^^^^^^^^^^^^^^^^^
  811. The class constructor, called on class instantiation, is named ``_init``.
  812. As mentioned earlier, the constructors of parent classes are called automatically when
  813. inheriting a class. So there is usually no need to call ``._init()`` explicitly.
  814. Unlike the call of a regular function, like in the above example with ``.some_func``,
  815. if the constructor from the inherited class takes arguments, they are passed like this:
  816. ::
  817. func _init(args).(parent_args):
  818. pass
  819. This is better explained through examples. Say we have this scenario:
  820. ::
  821. # State.gd (inherited class)
  822. var entity = null
  823. var message = null
  824. func _init(e=null):
  825. entity = e
  826. func enter(m):
  827. message = m
  828. # Idle.gd (inheriting class)
  829. extends "State.gd"
  830. func _init(e=null, m=null).(e):
  831. # Do something with 'e'.
  832. message = m
  833. There are a few things to keep in mind here:
  834. 1. if the inherited class (``State.gd``) defines a ``_init`` constructor that takes
  835. arguments (``e`` in this case), then the inheriting class (``Idle.gd``) *has* to
  836. define ``_init`` as well and pass appropriate parameters to ``_init`` from ``State.gd``
  837. 2. ``Idle.gd`` can have a different number of arguments than the base class ``State.gd``
  838. 3. in the example above, ``e`` passed to the ``State.gd`` constructor is the same ``e`` passed
  839. in to ``Idle.gd``
  840. 4. if ``Idle.gd``'s ``_init`` constructor takes 0 arguments, it still needs to pass some value
  841. to the ``State.gd`` base class even if it does nothing. Which brings us to the fact that you
  842. can pass literals in the base constructor as well, not just variables. Eg.:
  843. ::
  844. # Idle.gd
  845. func _init().(5):
  846. pass
  847. Inner classes
  848. ^^^^^^^^^^^^^
  849. A class file can contain inner classes. Inner classes are defined using the
  850. ``class`` keyword. They are instanced using the ``ClassName.new()``
  851. function.
  852. ::
  853. # Inside a class file.
  854. # An inner class in this class file.
  855. class SomeInnerClass:
  856. var a = 5
  857. func print_value_of_a():
  858. print(a)
  859. # This is the constructor of the class file's main class.
  860. func _init():
  861. var c = SomeInnerClass.new()
  862. c.print_value_of_a()
  863. Classes as resources
  864. ^^^^^^^^^^^^^^^^^^^^
  865. Classes stored as files are treated as :ref:`resources <class_GDScript>`. They
  866. must be loaded from disk to access them in other classes. This is done using
  867. either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
  868. class resource is done by calling the ``new`` function on the class object::
  869. # Load the class resource when calling load().
  870. var my_class = load("myclass.gd")
  871. # Preload the class only once at compile time.
  872. const MyClass = preload("myclass.gd")
  873. func _init():
  874. var a = MyClass.new()
  875. a.some_function()
  876. .. _doc_gdscript_exports:
  877. Exports
  878. ~~~~~~~
  879. Class members can be exported. This means their value gets saved along
  880. with the resource (e.g. the :ref:`scene <class_PackedScene>`) they're attached
  881. to. They will also be available for editing in the property editor. Exporting
  882. is done by using the ``export`` keyword::
  883. extends Button
  884. export var number = 5 # Value will be saved and visible in the property editor.
  885. An exported variable must be initialized to a constant expression or have an
  886. export hint in the form of an argument to the export keyword (see below).
  887. One of the fundamental benefits of exporting member variables is to have
  888. them visible and editable in the editor. This way, artists and game designers
  889. can modify values that later influence how the program runs. For this, a
  890. special export syntax is provided.
  891. ::
  892. # If the exported value assigns a constant or constant expression,
  893. # the type will be inferred and used in the editor.
  894. export var number = 5
  895. # Export can take a basic data type as an argument, which will be
  896. # used in the editor.
  897. export(int) var number
  898. # Export can also take a resource type to use as a hint.
  899. export(Texture) var character_face
  900. export(PackedScene) var scene_file
  901. # Integers and strings hint enumerated values.
  902. # Editor will enumerate as 0, 1 and 2.
  903. export(int, "Warrior", "Magician", "Thief") var character_class
  904. # Editor will enumerate with string names.
  905. export(String, "Rebecca", "Mary", "Leah") var character_name
  906. # Named Enum Values
  907. # Editor will enumerate as THING_1, THING_2, ANOTHER_THING.
  908. enum NamedEnum {THING_1, THING_2, ANOTHER_THING = -1}
  909. export (NamedEnum) var x
  910. # Strings as Paths
  911. # String is a path to a file.
  912. export(String, FILE) var f
  913. # String is a path to a directory.
  914. export(String, DIR) var f
  915. # String is a path to a file, custom filter provided as hint.
  916. export(String, FILE, "*.txt") var f
  917. # Using paths in the global filesystem is also possible,
  918. # but only in tool scripts (see further below).
  919. # String is a path to a PNG file in the global filesystem.
  920. export(String, FILE, GLOBAL, "*.png") var tool_image
  921. # String is a path to a directory in the global filesystem.
  922. export(String, DIR, GLOBAL) var tool_dir
  923. # The MULTILINE setting tells the editor to show a large input
  924. # field for editing over multiple lines.
  925. export(String, MULTILINE) var text
  926. # Limiting editor input ranges
  927. # Allow integer values from 0 to 20.
  928. export(int, 20) var i
  929. # Allow integer values from -10 to 20.
  930. export(int, -10, 20) var j
  931. # Allow floats from -10 to 20, with a step of 0.2.
  932. export(float, -10, 20, 0.2) var k
  933. # Allow values y = exp(x) where y varies between 100 and 1000
  934. # while snapping to steps of 20. The editor will present a
  935. # slider for easily editing the value.
  936. export(float, EXP, 100, 1000, 20) var l
  937. # Floats with Easing Hint
  938. # Display a visual representation of the ease() function
  939. # when editing.
  940. export(float, EASE) var transition_speed
  941. # Colors
  942. # Color given as Red-Green-Blue value
  943. export(Color, RGB) var col # Color is RGB.
  944. # Color given as Red-Green-Blue-Alpha value
  945. export(Color, RGBA) var col # Color is RGBA.
  946. # Another node in the scene can be exported, too.
  947. export(NodePath) var node
  948. It must be noted that even if the script is not being run while at the
  949. editor, the exported properties are still editable (see below for
  950. "tool").
  951. Exporting bit flags
  952. ^^^^^^^^^^^^^^^^^^^
  953. Integers used as bit flags can store multiple ``true``/``false`` (boolean)
  954. values in one property. By using the export hint ``int, FLAGS``, they
  955. can be set from the editor:
  956. ::
  957. # Individually edit the bits of an integer.
  958. export(int, FLAGS) var spell_elements = ELEMENT_WIND | ELEMENT_WATER
  959. Restricting the flags to a certain number of named flags is also
  960. possible. The syntax is similar to the enumeration syntax:
  961. ::
  962. # Set any of the given flags from the editor.
  963. export(int, FLAGS, "Fire", "Water", "Earth", "Wind") var spell_elements = 0
  964. In this example, ``Fire`` has value 1, ``Water`` has value 2, ``Earth``
  965. has value 4 and ``Wind`` corresponds to value 8. Usually, constants
  966. should be defined accordingly (e.g. ``const ELEMENT_WIND = 8`` and so
  967. on).
  968. Using bit flags requires some understanding of bitwise operations. If in
  969. doubt, boolean variables should be exported instead.
  970. Exporting arrays
  971. ^^^^^^^^^^^^^^^^
  972. Exporting arrays works, but with an important caveat: While regular
  973. arrays are created local to every class instance, exported arrays are *shared*
  974. between all instances. This means that editing them in one instance will
  975. cause them to change in all other instances. Exported arrays can have
  976. initializers, but they must be constant expressions.
  977. ::
  978. # Exported array, shared between all instances.
  979. # Default value must be a constant expression.
  980. export var a = [1, 2, 3]
  981. # Exported arrays can specify type (using the same hints as before).
  982. export(Array, int) var ints = [1,2,3]
  983. export(Array, int, "Red", "Green", "Blue") var enums = [2, 1, 0]
  984. export(Array, Array, float) var two_dimensional = [[1, 2], [3, 4]]
  985. # You can omit the default value, but then it would be null if not assigned.
  986. export(Array) var b
  987. export(Array, PackedScene) var scenes
  988. # Typed arrays also work, only initialized empty:
  989. export var vector3s = PoolVector3Array()
  990. export var strings = PoolStringArray()
  991. # Regular array, created local for every instance.
  992. # Default value can include run-time values, but can't
  993. # be exported.
  994. var c = [a, 2, 3]
  995. Setters/getters
  996. ~~~~~~~~~~~~~~~
  997. It is often useful to know when a class' member variable changes for
  998. whatever reason. It may also be desired to encapsulate its access in some way.
  999. For this, GDScript provides a *setter/getter* syntax using the ``setget`` keyword.
  1000. It is used directly after a variable definition:
  1001. ::
  1002. var variable = value setget setterfunc, getterfunc
  1003. Whenever the value of ``variable`` is modified by an *external* source
  1004. (i.e. not from local usage in the class), the *setter* function (``setterfunc`` above)
  1005. will be called. This happens *before* the value is changed. The *setter* must decide what to do
  1006. with the new value. Vice versa, when ``variable`` is accessed, the *getter* function
  1007. (``getterfunc`` above) must ``return`` the desired value. Below is an example:
  1008. ::
  1009. var myvar setget my_var_set, my_var_get
  1010. func my_var_set(new_value):
  1011. my_var = new_value
  1012. func my_var_get():
  1013. return my_var # Getter must return a value.
  1014. Either of the *setter* or *getter* functions can be omitted:
  1015. ::
  1016. # Only a setter.
  1017. var my_var = 5 setget myvar_set
  1018. # Only a getter (note the comma).
  1019. var my_var = 5 setget ,myvar_get
  1020. Get/Setters are especially useful when exporting variables to editor in tool
  1021. scripts or plugins, for validating input.
  1022. As said, *local* access will *not* trigger the setter and getter. Here is an
  1023. illustration of this:
  1024. ::
  1025. func _init():
  1026. # Does not trigger setter/getter.
  1027. my_integer = 5
  1028. print(my_integer)
  1029. # Does trigger setter/getter.
  1030. self.my_integer = 5
  1031. print(self.my_integer)
  1032. Tool mode
  1033. ~~~~~~~~~
  1034. Scripts, by default, don't run inside the editor and only the exported
  1035. properties can be changed. In some cases, it is desired that they do run
  1036. inside the editor (as long as they don't execute game code or manually
  1037. avoid doing so). For this, the ``tool`` keyword exists and must be
  1038. placed at the top of the file:
  1039. ::
  1040. tool
  1041. extends Button
  1042. func _ready():
  1043. print("Hello")
  1044. Memory management
  1045. ~~~~~~~~~~~~~~~~~
  1046. If a class inherits from :ref:`class_Reference`, then instances will be
  1047. freed when no longer in use. No garbage collector exists, just
  1048. reference counting. By default, all classes that don't define
  1049. inheritance extend **Reference**. If this is not desired, then a class
  1050. must inherit :ref:`class_Object` manually and must call instance.free(). To
  1051. avoid reference cycles that can't be freed, a ``weakref`` function is
  1052. provided for creating weak references.
  1053. Alternatively, when not using references, the
  1054. ``is_instance_valid(instance)`` can be used to check if an object has been
  1055. freed.
  1056. .. _doc_gdscript_signals:
  1057. Signals
  1058. ~~~~~~~
  1059. It is often desired to send a notification that something happened in an
  1060. instance. GDScript supports creation of built-in Godot signals.
  1061. Declaring a signal in GDScript is easy using the `signal` keyword.
  1062. ::
  1063. # No arguments.
  1064. signal your_signal_name
  1065. # With arguments.
  1066. signal your_signal_name_with_args(a, b)
  1067. These signals can be connected in the editor or from code like regular signals.
  1068. Take the instance of a class where the signal was
  1069. declared and connect it to the method of another instance:
  1070. ::
  1071. func _callback_no_args():
  1072. print("Got callback!")
  1073. func _callback_args(a,b):
  1074. print("Got callback with args! a: ", a, " and b: ", b)
  1075. func _at_some_func():
  1076. instance.connect("your_signal_name", self, "_callback_no_args")
  1077. instance.connect("your_signal_name_with_args", self, "_callback_args")
  1078. It is also possible to bind arguments to a signal that lacks them with
  1079. your custom values:
  1080. ::
  1081. func _at_some_func():
  1082. instance.connect("your_signal_name", self, "_callback_args", [22, "hello"])
  1083. This is useful when a signal from many objects is connected to a
  1084. single callback and the sender must be identified:
  1085. ::
  1086. func _button_pressed(which):
  1087. print("Button was pressed: ", which.get_name())
  1088. func _ready():
  1089. for b in get_node("buttons").get_children():
  1090. b.connect("pressed", self, "_button_pressed",[b])
  1091. Finally, emitting a custom signal is done by using the
  1092. Object.emit_signal method:
  1093. ::
  1094. func _at_some_func():
  1095. emit_signal("your_signal_name")
  1096. emit_signal("your_signal_name_with_args", 55, 128)
  1097. some_instance.emit_signal("some_signal")
  1098. Coroutines with yield
  1099. ~~~~~~~~~~~~~~~~~~~~~
  1100. GDScript offers support for `coroutines <https://en.wikipedia.org/wiki/Coroutine>`_
  1101. via the ``yield`` built-in function. Calling ``yield()`` will
  1102. immediately return from the current function, with the current frozen
  1103. state of the same function as the return value. Calling ``resume`` on
  1104. this resulting object will continue execution and return whatever the
  1105. function returns. Once resumed, the state object becomes invalid. Here is
  1106. an example:
  1107. ::
  1108. func my_func():
  1109. print("Hello")
  1110. yield()
  1111. print("world")
  1112. func _ready():
  1113. var y = my_func()
  1114. # Function state saved in 'y'.
  1115. print("my dear")
  1116. y.resume()
  1117. # 'y' resumed and is now an invalid state.
  1118. Will print:
  1119. ::
  1120. Hello
  1121. my dear
  1122. world
  1123. It is also possible to pass values between yield() and resume(), for
  1124. example:
  1125. ::
  1126. func my_func():
  1127. print("Hello")
  1128. print(yield())
  1129. return "cheers!"
  1130. func _ready():
  1131. var y = my_func()
  1132. # Function state saved in 'y'.
  1133. print(y.resume("world"))
  1134. # 'y' resumed and is now an invalid state.
  1135. Will print:
  1136. ::
  1137. Hello
  1138. world
  1139. cheers!
  1140. Coroutines & signals
  1141. ^^^^^^^^^^^^^^^^^^^^
  1142. The real strength of using ``yield`` is when combined with signals.
  1143. ``yield`` can accept two arguments, an object and a signal. When the
  1144. signal is received, execution will recommence. Here are some examples:
  1145. ::
  1146. # Resume execution the next frame.
  1147. yield(get_tree(), "idle_frame")
  1148. # Resume execution when animation is done playing.
  1149. yield(get_node("AnimationPlayer"), "finished")
  1150. # Wait 5 seconds, then resume execution.
  1151. yield(get_tree().create_timer(5.0), "timeout")
  1152. Coroutines themselves use the ``completed`` signal when they transition
  1153. into an invalid state, for example:
  1154. ::
  1155. func my_func():
  1156. yield(button_func(), "completed")
  1157. print("All buttons were pressed, hurray!")
  1158. func button_func():
  1159. yield($Button0, "pressed")
  1160. yield($Button1, "pressed")
  1161. ``my_func`` will only continue execution once both buttons have been pressed.
  1162. Onready keyword
  1163. ~~~~~~~~~~~~~~~
  1164. When using nodes, it's common to desire to keep references to parts
  1165. of the scene in a variable. As scenes are only warranted to be
  1166. configured when entering the active scene tree, the sub-nodes can only
  1167. be obtained when a call to Node._ready() is made.
  1168. ::
  1169. var my_label
  1170. func _ready():
  1171. my_label = get_node("MyLabel")
  1172. This can get a little cumbersome, especially when nodes and external
  1173. references pile up. For this, GDScript has the ``onready`` keyword, that
  1174. defers initialization of a member variable until _ready is called. It
  1175. can replace the above code with a single line:
  1176. ::
  1177. onready var my_label = get_node("MyLabel")
  1178. Assert keyword
  1179. ~~~~~~~~~~~~~~
  1180. The ``assert`` keyword can be used to check conditions in debug builds.
  1181. These assertions are ignored in non-debug builds.
  1182. ::
  1183. # Check that 'i' is 0.
  1184. assert(i == 0)