2
0

gdscript_basics.rst 61 KB

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