gdscript_basics.rst 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  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. Initially, Godot was designed to support multiple scripting languages
  15. (this ability still exists today). However, only GDScript is in use
  16. right now. There is a little history behind this.
  17. In the early days, the engine used the `Lua <http://www.lua.org>`__
  18. scripting language. Lua is fast, but creating bindings to an object
  19. oriented system (by using fallbacks) was complex and slow and took an
  20. enormous amount of code. After some experiments with
  21. `Python <http://www.python.org>`__, it also proved difficult to embed.
  22. The last third party scripting language that was used for shipped games
  23. was `Squirrel <http://squirrel-lang.org>`__, but it was dropped as well.
  24. At that point, it became evident that a custom scripting language could
  25. more optimally make use of Godot's particular architecture:
  26. - Godot embeds scripts in nodes. Most languages are not designed with
  27. this in mind.
  28. - Godot uses several built-in data types for 2D and 3D math. Script
  29. languages do not provide this, and binding them is inefficient.
  30. - Godot uses threads heavily for lifting and initializing data from the
  31. net or disk. Script interpreters for common languages are not
  32. friendly to this.
  33. - Godot already has a memory management model for resources, most
  34. script languages provide their own, which results in duplicate
  35. effort and bugs.
  36. - Binding code is always messy and results in several failure points,
  37. unexpected bugs and generally low maintainability.
  38. The result of these considerations is *GDScript*. The language and
  39. interpreter for GDScript ended up being smaller than the binding code itself
  40. for Lua and Squirrel, while having equal functionality. With time, having a
  41. built-in language has proven to be a huge advantage.
  42. Example of GDScript
  43. ~~~~~~~~~~~~~~~~~~~
  44. Some people can learn better by just taking a look at the syntax, so
  45. here's a simple example of how GDScript looks.
  46. ::
  47. # a file is a class!
  48. # inheritance
  49. extends BaseClass
  50. # member variables
  51. var a = 5
  52. var s = "Hello"
  53. var arr = [1, 2, 3]
  54. var dict = {"key":"value", 2:3}
  55. # constants
  56. const answer = 42
  57. const thename = "Charly"
  58. # enums
  59. enum {UNIT_NEUTRAL, UNIT_ENEMY, UNIT_ALLY}
  60. enum Named {THING_1, THING_2, ANOTHER_THING = -1}
  61. # built-in vector types
  62. var v2 = Vector2(1, 2)
  63. var v3 = Vector3(1, 2, 3)
  64. # function
  65. func some_function(param1, param2):
  66. var local_var = 5
  67. if param1 < local_var:
  68. print(param1)
  69. elif param2 > 5:
  70. print(param2)
  71. else:
  72. print("fail!")
  73. for i in range(20):
  74. print(i)
  75. while(param2 != 0):
  76. param2 -= 1
  77. var local_var2 = param1+3
  78. return local_var2
  79. # inner class
  80. class Something:
  81. var a = 10
  82. # constructor
  83. func _init():
  84. print("constructed!")
  85. var lv = Something.new()
  86. print(lv.a)
  87. If you have previous experience with statically typed languages such as
  88. C, C++, or C# but never used a dynamically typed one before, it is advised you
  89. read this tutorial: :ref:`doc_gdscript_more_efficiently`.
  90. Language
  91. --------
  92. In the following, an overview is given to GDScript. Details, such as which
  93. methods are available to arrays or other objects, should be looked up in
  94. the linked class descriptions.
  95. Identifiers
  96. ~~~~~~~~~~~
  97. Any string that restricts itself to alphabetic characters (``a`` to
  98. ``z`` and ``A`` to ``Z``), digits (``0`` to ``9``) and ``_`` qualifies
  99. as an identifier. Additionally, identifiers must not begin with a digit.
  100. Identifiers are case-sensitive (``foo`` is different from ``FOO``).
  101. Keywords
  102. ~~~~~~~~
  103. The following is the list of keywords supported by the language. Since
  104. keywords are reserved words (tokens), they can't be used as identifiers.
  105. +------------+---------------------------------------------------------------------------------------------------------------+
  106. | Keyword | Description |
  107. +============+===============================================================================================================+
  108. | if | See `if/else/elif`_. |
  109. +------------+---------------------------------------------------------------------------------------------------------------+
  110. | elif | See `if/else/elif`_. |
  111. +------------+---------------------------------------------------------------------------------------------------------------+
  112. | else | See `if/else/elif`_. |
  113. +------------+---------------------------------------------------------------------------------------------------------------+
  114. | for | See for_. |
  115. +------------+---------------------------------------------------------------------------------------------------------------+
  116. | do | Reserved for future implementation of do...while loops. |
  117. +------------+---------------------------------------------------------------------------------------------------------------+
  118. | while | See while_. |
  119. +------------+---------------------------------------------------------------------------------------------------------------+
  120. | match | See match_. |
  121. +------------+---------------------------------------------------------------------------------------------------------------+
  122. | switch | Reserved for future implementation. |
  123. +------------+---------------------------------------------------------------------------------------------------------------+
  124. | case | Reserved for future implementation. |
  125. +------------+---------------------------------------------------------------------------------------------------------------+
  126. | break | Exits the execution of the current ``for`` or ``while`` loop. |
  127. +------------+---------------------------------------------------------------------------------------------------------------+
  128. | continue | Immediately skips to the next iteration of the ``for`` or ``while`` loop. |
  129. +------------+---------------------------------------------------------------------------------------------------------------+
  130. | pass | Used where a statement is required syntactically but execution of code is undesired, e.g. in empty functions. |
  131. +------------+---------------------------------------------------------------------------------------------------------------+
  132. | return | Returns a value from a function. |
  133. +------------+---------------------------------------------------------------------------------------------------------------+
  134. | class | Defines a class. |
  135. +------------+---------------------------------------------------------------------------------------------------------------+
  136. | extends | Defines what class to extend with the current class. Also tests whether a variable extends a given class. |
  137. +------------+---------------------------------------------------------------------------------------------------------------+
  138. | tool | Executes the script in the editor. |
  139. +------------+---------------------------------------------------------------------------------------------------------------+
  140. | signal | Defines a signal. |
  141. +------------+---------------------------------------------------------------------------------------------------------------+
  142. | func | Defines a function. |
  143. +------------+---------------------------------------------------------------------------------------------------------------+
  144. | static | Defines a static function. Static member variables are not allowed. |
  145. +------------+---------------------------------------------------------------------------------------------------------------+
  146. | const | Defines a constant. |
  147. +------------+---------------------------------------------------------------------------------------------------------------+
  148. | enum | Defines an enum. |
  149. +------------+---------------------------------------------------------------------------------------------------------------+
  150. | var | Defines a variable. |
  151. +------------+---------------------------------------------------------------------------------------------------------------+
  152. | onready | Initializes a variable once the Node the script is attached to and its children are part of the scene tree. |
  153. +------------+---------------------------------------------------------------------------------------------------------------+
  154. | export | Saves a variable along with the resource it's attached to and makes it visible and modifiable in the editor. |
  155. +------------+---------------------------------------------------------------------------------------------------------------+
  156. | setget | Defines setter and getter functions for a variable. |
  157. +------------+---------------------------------------------------------------------------------------------------------------+
  158. | breakpoint | Editor helper for debugger breakpoints. |
  159. +------------+---------------------------------------------------------------------------------------------------------------+
  160. Operators
  161. ~~~~~~~~~
  162. The following is the list of supported operators and their precedence
  163. (TODO, change since this was made to reflect python operators)
  164. +---------------------------------------------------------------+-----------------------------------------+
  165. | **Operator** | **Description** |
  166. +---------------------------------------------------------------+-----------------------------------------+
  167. | ``x[index]`` | Subscription, Highest Priority |
  168. +---------------------------------------------------------------+-----------------------------------------+
  169. | ``x.attribute`` | Attribute Reference |
  170. +---------------------------------------------------------------+-----------------------------------------+
  171. | ``extends`` | Instance Type Checker |
  172. +---------------------------------------------------------------+-----------------------------------------+
  173. | ``~`` | Bitwise NOT |
  174. +---------------------------------------------------------------+-----------------------------------------+
  175. | ``-x`` | Negative |
  176. +---------------------------------------------------------------+-----------------------------------------+
  177. | ``*`` ``/`` ``%`` | Multiplication / Division / Remainder |
  178. | | |
  179. | | NOTE: The result of these operations |
  180. | | depends on the operands types. If both |
  181. | | are Integers, then the result will be |
  182. | | an Integer. That means 1/10 returns 0 |
  183. | | instead of 0.1. If at least one of the |
  184. | | operands is a float, then the result is |
  185. | | a float: float(1)/10 or 1.0/10 return |
  186. | | both 0.1. |
  187. +---------------------------------------------------------------+-----------------------------------------+
  188. | ``+`` ``-`` | Addition / Subtraction |
  189. +---------------------------------------------------------------+-----------------------------------------+
  190. | ``<<`` ``>>`` | Bit Shifting |
  191. +---------------------------------------------------------------+-----------------------------------------+
  192. | ``&`` | Bitwise AND |
  193. +---------------------------------------------------------------+-----------------------------------------+
  194. | ``^`` | Bitwise XOR |
  195. +---------------------------------------------------------------+-----------------------------------------+
  196. | ``|`` | Bitwise OR |
  197. +---------------------------------------------------------------+-----------------------------------------+
  198. | ``<`` ``>`` ``==`` ``!=`` ``>=`` ``<=`` | Comparisons |
  199. +---------------------------------------------------------------+-----------------------------------------+
  200. | ``in`` | Content Test |
  201. +---------------------------------------------------------------+-----------------------------------------+
  202. | ``!`` ``not`` | Boolean NOT |
  203. +---------------------------------------------------------------+-----------------------------------------+
  204. | ``and`` ``&&`` | Boolean AND |
  205. +---------------------------------------------------------------+-----------------------------------------+
  206. | ``or`` ``||`` | Boolean OR |
  207. +---------------------------------------------------------------+-----------------------------------------+
  208. | ``if x else`` | Ternary if/else |
  209. +---------------------------------------------------------------+-----------------------------------------+
  210. | ``=`` ``+=`` ``-=`` ``*=`` ``/=`` ``%=`` ``&=`` ``|=`` | Assignment, Lowest Priority |
  211. +---------------------------------------------------------------+-----------------------------------------+
  212. Literals
  213. ~~~~~~~~
  214. +--------------------------+--------------------------------+
  215. | **Literal** | **Type** |
  216. +--------------------------+--------------------------------+
  217. | ``45`` | Base 10 integer |
  218. +--------------------------+--------------------------------+
  219. | ``0x8F51`` | Base 16 (hex) integer |
  220. +--------------------------+--------------------------------+
  221. | ``3.14``, ``58.1e-10`` | Floating point number (real) |
  222. +--------------------------+--------------------------------+
  223. | ``"Hello"``, ``"Hi"`` | Strings |
  224. +--------------------------+--------------------------------+
  225. | ``"""Hello, Dude"""`` | Multiline string |
  226. +--------------------------+--------------------------------+
  227. | ``@"Node/Label"`` | NodePath or StringName |
  228. +--------------------------+--------------------------------+
  229. Comments
  230. ~~~~~~~~
  231. Anything from a ``#`` to the end of the line is ignored and is
  232. considered a comment.
  233. ::
  234. # This is a comment
  235. .. Uncomment me if/when https://github.com/godotengine/godot/issues/1320 gets fixed
  236. Multi-line comments can be created using """ (three quotes in a row) at
  237. the beginning and end of a block of text.
  238. ::
  239. """ Everything on these
  240. lines is considered
  241. a comment """
  242. Built-in types
  243. --------------
  244. Basic built-in types
  245. ~~~~~~~~~~~~~~~~~~~~
  246. A variable in GDScript can be assigned to several built-in types.
  247. null
  248. ^^^^
  249. ``null`` is an empty data type that contains no information and can not
  250. be assigned any other value.
  251. bool
  252. ^^^^
  253. The Boolean data type can only contain ``true`` or ``false``.
  254. int
  255. ^^^
  256. The integer data type can only contain integer numbers, (both negative
  257. and positive).
  258. float
  259. ^^^^^
  260. Used to contain a floating point value (real numbers).
  261. :ref:`String <class_String>`
  262. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  263. A sequence of characters in `Unicode format <https://en.wikipedia.org/wiki/Unicode>`_. Strings can contain the
  264. `standard C escape sequences <https://en.wikipedia.org/wiki/Escape_sequences_in_C>`_.
  265. GDScript supports :ref:`format strings aka printf functionality
  266. <doc_gdscript_printf>`.
  267. Vector built-in types
  268. ~~~~~~~~~~~~~~~~~~~~~
  269. :ref:`Vector2 <class_Vector2>`
  270. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  271. 2D vector type containing ``x`` and ``y`` fields. Can alternatively
  272. access fields as ``width`` and ``height`` for readability. Can also be
  273. accessed as array.
  274. :ref:`Rect2 <class_Rect2>`
  275. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  276. 2D Rectangle type containing two vectors fields: ``pos`` and ``size``.
  277. Alternatively contains an ``end`` field which is ``pos+size``.
  278. :ref:`Vector3 <class_Vector3>`
  279. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  280. 3D vector type containing ``x``, ``y`` and ``z`` fields. This can also
  281. be accessed as an array.
  282. :ref:`Matrix32 <class_Matrix32>`
  283. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  284. 3x2 matrix used for 2D transforms.
  285. :ref:`Plane <class_Plane>`
  286. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  287. 3D Plane type in normalized form that contains a ``normal`` vector field
  288. and a ``d`` scalar distance.
  289. :ref:`Quat <class_Quat>`
  290. ^^^^^^^^^^^^^^^^^^^^^^^^
  291. Quaternion is a datatype used for representing a 3D rotation. It's
  292. useful for interpolating rotations.
  293. :ref:`AABB <class_AABB>`
  294. ^^^^^^^^^^^^^^^^^^^^^^^^
  295. Axis Aligned bounding box (or 3D box) contains 2 vectors fields: ``pos``
  296. and ``size``. Alternatively contains an ``end`` field which is
  297. ``pos+size``. As an alias of this type, ``Rect3`` can be used
  298. interchangeably.
  299. :ref:`Matrix3 <class_Matrix3>`
  300. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  301. 3x3 matrix used for 3D rotation and scale. It contains 3 vector fields
  302. (``x``, ``y`` and ``z``) and can also be accessed as an array of 3D
  303. vectors.
  304. :ref:`Transform <class_Transform>`
  305. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  306. 3D Transform contains a Matrix3 field ``basis`` and a Vector3 field
  307. ``origin``.
  308. Engine built-in types
  309. ~~~~~~~~~~~~~~~~~~~~~
  310. :ref:`Color <class_Color>`
  311. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  312. Color data type contains ``r``, ``g``, ``b``, and ``a`` fields. It can
  313. also be accessed as ``h``, ``s``, and ``v`` for hue/saturation/value.
  314. :ref:`Image <class_Image>`
  315. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  316. Contains a custom format 2D image and allows direct access to the
  317. pixels.
  318. :ref:`NodePath <class_NodePath>`
  319. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  320. Compiled path to a node used mainly in the scene system. It can be
  321. easily assigned to, and from, a String.
  322. :ref:`RID <class_RID>`
  323. ^^^^^^^^^^^^^^^^^^^^^^
  324. Resource ID (RID). Servers use generic RIDs to reference opaque data.
  325. :ref:`Object <class_Object>`
  326. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  327. Base class for anything that is not a built-in type.
  328. :ref:`InputEvent <class_InputEvent>`
  329. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  330. Events from input devices are contained in very compact form in
  331. InputEvent objects. Due to the fact that they can be received in high
  332. amounts from frame to frame they are optimized as their own data type.
  333. Container built-in types
  334. ~~~~~~~~~~~~~~~~~~~~~~~~
  335. :ref:`Array <class_Array>`
  336. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  337. Generic sequence of arbitrary object types, including other arrays or dictionaries (see below).
  338. The array can resize dynamically. Arrays are indexed starting from index ``0``.
  339. Starting with Godot 2.1, indices may be negative like in Python, to count from the end.
  340. ::
  341. var arr=[]
  342. arr=[1, 2, 3]
  343. var b = arr[1] # this is 2
  344. var c = arr[arr.size()-1] # this is 3
  345. var d = arr[-1] # same as the previous line, but shorter
  346. arr[0] = "Hi!" # replacing value 1 with "Hi"
  347. arr.append(4) # array is now ["Hi", 2, 3, 4]
  348. GDScript arrays are allocated linearly in memory for speed. Very
  349. large arrays (more than tens of thousands of elements) may however cause
  350. memory fragmentation. If this is a concern special types of
  351. arrays are available. These only accept a single data type. They avoid memory
  352. fragmentation and also use less memory but are atomic and tend to run slower than generic
  353. arrays. They are therefore only recommended to use for very large data sets:
  354. - :ref:`ByteArray <class_ByteArray>`: An array of bytes (integers from 0 to 255).
  355. - :ref:`IntArray <class_IntArray>`: An array of integers.
  356. - :ref:`FloatArray <class_FloatArray>`: An array of floats.
  357. - :ref:`StringArray <class_StringArray>`: An array of strings.
  358. - :ref:`Vector2Array <class_Vector2Array>`: An array of :ref:`Vector2 <class_Vector2>` objects.
  359. - :ref:`Vector3Array <class_Vector3Array>`: An array of :ref:`Vector3 <class_Vector3>` objects.
  360. - :ref:`ColorArray <class_ColorArray>`: An array of :ref:`Color <class_Color>` objects.
  361. :ref:`Dictionary <class_Dictionary>`
  362. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  363. Associative container which contains values referenced by unique keys.
  364. ::
  365. var d={4:5, "a key":"a value", 28:[1,2,3]}
  366. d["Hi!"] = 0
  367. var d = {
  368. 22 : "Value",
  369. "somekey" : 2,
  370. "otherkey" : [2,3,4],
  371. "morekey" : "Hello"
  372. }
  373. Lua-style table syntax is also supported. Lua-style uses ``=`` instead of ``:``
  374. and doesn't use quotes to mark string keys (making for slightly less to write).
  375. Note however that like any GDScript identifier, keys written in this form cannot
  376. start with a digit.
  377. ::
  378. var d = {
  379. test22 = "Value",
  380. somekey = 2,
  381. otherkey = [2,3,4],
  382. morekey = "Hello"
  383. }
  384. To add a key to an existing dictionary, access it like an existing key and
  385. assign to it::
  386. var d = {} # create an empty Dictionary
  387. d.Waiting = 14 # add String "Waiting" as a key and assign the value 14 to it
  388. d[4] = "hello" # add integer `4` as a key and assign the String "hello" as its value
  389. d["Godot"] = 3.01 # add String "Godot" as a key and assign the value 3.01 to it
  390. Data
  391. ----
  392. Variables
  393. ~~~~~~~~~
  394. Variables can exist as class members or local to functions. They are
  395. created with the ``var`` keyword and may, optionally, be assigned a
  396. value upon initialization.
  397. ::
  398. var a # data type is null by default
  399. var b = 5
  400. var c = 3.8
  401. var d = b + c # variables are always initialized in order
  402. Constants
  403. ~~~~~~~~~
  404. Constants are similar to variables, but must be constants or constant
  405. expressions and must be assigned on initialization.
  406. ::
  407. const a = 5
  408. const b = Vector2(20, 20)
  409. const c = 10 + 20 # constant expression
  410. const d = Vector2(20, 30).x # constant expression: 20
  411. const e = [1, 2, 3, 4][0] # constant expression: 1
  412. const f = sin(20) # sin() can be used in constant expressions
  413. const g = x + 20 # invalid; this is not a constant expression!
  414. Enums
  415. ^^^^^
  416. Enums are basically a shorthand for constants, and are pretty useful if you
  417. want to assign consecutive integers to some constant.
  418. If you pass a name to the enum, it would also put all the values inside a
  419. constant dictionary of that name.
  420. ::
  421. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  422. # Is the same as:
  423. const TILE_BRICK = 0
  424. const TILE_FLOOR = 1
  425. const TILE_SPIKE = 2
  426. const TILE_TELEPORT = 3
  427. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  428. # Is the same as:
  429. const STATE_IDLE = 0
  430. const STATE_JUMP = 5
  431. const STATE_SHOOT = 6
  432. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  433. Functions
  434. ~~~~~~~~~
  435. Functions always belong to a `class <Classes_>`_. The scope priority for
  436. variable look-up is: local → class member → global. The ``self`` variable is
  437. always available and is provided as an option for accessing class members, but
  438. is not always required (and should *not* be sent as the function's first
  439. argument, unlike Python).
  440. ::
  441. func myfunction(a, b):
  442. print(a)
  443. print(b)
  444. return a + b # return is optional; without it null is returned
  445. A function can ``return`` at any point. The default return value is ``null``.
  446. Referencing Functions
  447. ^^^^^^^^^^^^^^^^^^^^^
  448. To call a function in a *base class* (i.e. one ``extend``-ed in your current class),
  449. prepend ``.`` to the function name:
  450. ::
  451. .basefunc(args)
  452. Contrary to Python, functions are *not* first class objects in GDScript. This
  453. means they cannot be stored in variables, passed as an argument to another
  454. function or be returned from other functions. This is for performance reasons.
  455. To reference a function by name at runtime, (e.g. to store it in a variable, or
  456. pass it to another function as an argument) one must use the ``call`` or
  457. ``funcref`` helpers::
  458. # Call a function by name in one step
  459. mynode.call("myfunction", args)
  460. # Store a function reference
  461. var myfunc = funcref(mynode, "myfunction")
  462. # Call stored function reference
  463. myfunc.call_func(args)
  464. Remember that default functions like ``_init``, and most
  465. notifications such as ``_enter_tree``, ``_exit_tree``, ``_process``,
  466. ``_fixed_process``, etc. are called in all base classes automatically.
  467. So there is only a need to call the function explicitly when overloading
  468. them in some way.
  469. Static functions
  470. ^^^^^^^^^^^^^^^^
  471. A function can be declared static. When a function is static it has no
  472. access to the instance member variables or ``self``. This is mainly
  473. useful to make libraries of helper functions:
  474. ::
  475. static func sum2(a, b):
  476. return a + b
  477. Statements and control flow
  478. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  479. Statements are standard and can be assignments, function calls, control
  480. flow structures, etc (see below). ``;`` as a statement separator is
  481. entirely optional.
  482. if/else/elif
  483. ^^^^^^^^^^^^
  484. Simple conditions are created by using the ``if``/``else``/``elif`` syntax.
  485. Parenthesis around conditions are allowed, but not required. Given the
  486. nature of the tab-based indentation, ``elif`` can be used instead of
  487. ``else``/``if`` to maintain a level of indentation.
  488. ::
  489. if [expression]:
  490. statement(s)
  491. elif [expression]:
  492. statement(s)
  493. else:
  494. statement(s)
  495. Short statements can be written on the same line as the condition::
  496. if (1 + 1 == 2): return 2 + 2
  497. else:
  498. var x = 3 + 3
  499. return x
  500. Sometimes you might want to assign a different initial value based on a
  501. boolean expression. In this case ternary-if expressions come in handy::
  502. var x = [true-value] if [expression] else [false-value]
  503. y += 3 if y < 10 else -1
  504. while
  505. ^^^^^
  506. Simple loops are created by using ``while`` syntax. Loops can be broken
  507. using ``break`` or continued using ``continue``:
  508. ::
  509. while [expression]:
  510. statement(s)
  511. for
  512. ^^^
  513. To iterate through a range, such as an array or table, a *for* loop is
  514. used. When iterating over an array, the current array element is stored in
  515. the loop variable. When iterating over a dictionary, the *index* is stored
  516. in the loop variable.
  517. ::
  518. for x in [5, 7, 11]:
  519. statement # loop iterates 3 times with x as 5, then 7 and finally 11
  520. var dict = {"a":0, "b":1, "c":2}
  521. for i in dict:
  522. print(dict[i]) # loop provides the keys in an arbitrary order; may print 0, 1, 2, or 2, 0, 1, etc...
  523. for i in range(3):
  524. statement # similar to [0, 1, 2] but does not allocate an array
  525. for i in range(1,3):
  526. statement # similar to [1, 2] but does not allocate an array
  527. for i in range(2,8,2):
  528. statement # similar to [2, 4, 6] but does not allocate an array
  529. for c in "Hello":
  530. print(c) # iterate through all characters in a String, print every letter on new line
  531. match
  532. ^^^^^
  533. A ``match`` statement is used to branch execution of a program.
  534. It's the equivalent of the ``switch`` statement found in many other languages but offers some additional features.
  535. Basic syntax:
  536. ::
  537. match [expression]:
  538. [pattern](s): [block]
  539. [pattern](s): [block]
  540. [pattern](s): [block]
  541. **Crash-course for people who are familiar to switch statements**:
  542. 1. Replace ``switch`` with ``match``
  543. 2. Remove ``case``
  544. 3. Remove any ``break``'s. If you don't want to ``break`` by default you can use ``continue`` for a fallthrough.
  545. 4. Change ``default`` to a single underscore.
  546. **Control flow**:
  547. The patterns are matched from top to bottom.
  548. If a pattern matches, the corresponding block will be executed. After that, the execution continues below the ``match`` statement.
  549. If you want to have a fallthrough you can use ``continue`` to stop execution in the current block and check the ones below it.
  550. There are 6 pattern types:
  551. - constant pattern
  552. constant primitives, like numbers and strings ::
  553. match x:
  554. 1: print("We are number one!")
  555. 2: print("Two are better than one!")
  556. "test": print("Oh snap! It's a string!")
  557. - variable pattern
  558. matches the contents of a variable/enum ::
  559. match typeof(x):
  560. TYPE_FLOAT: print("float")
  561. TYPE_STRING: print("text")
  562. TYPE_ARRAY: print("array")
  563. - wildcard pattern
  564. This pattern matches everything. It's written as a single underscore.
  565. It can be used as the equivalent of the ``default`` in a ``switch`` statement in other languages. ::
  566. match x:
  567. 1: print("it's one!")
  568. 2: print("it's one times two!")
  569. _: print("it's not 1 or 2. I don't care tbh.")
  570. - binding pattern
  571. A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name.
  572. It's especially useful in array and dictionary patterns. ::
  573. match x:
  574. 1: print("it's one!")
  575. 2: print("it's one times two!")
  576. var new_var: print("it's not 1 or 2, it's ", new_var)
  577. - array pattern
  578. matches an array. Every single element of the array pattern is a pattern itself so you can nest them.
  579. The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern don't match.
  580. **Open-ended array**: An array can be bigger than the pattern by making the last subpattern ``..``
  581. Every subpattern has to be comma separated. ::
  582. match x:
  583. []:
  584. print("empty array")
  585. [1, 3, "test", null]:
  586. print("very specific array")
  587. [var start, _, "test"]:
  588. print("first element is ", start, ", and the last is \"test\"")
  589. [42, ..]:
  590. print("open ended array")
  591. - dictionary pattern
  592. Works in the same was as the array pattern. Every key has to be a constant pattern.
  593. The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern don't match.
  594. **Open-ended dictionary**: A dictionary can be bigger than the pattern by making the last subpattern ``..``
  595. Every subpattern has to be comma separated.
  596. If you don't specify a value, then only the existence of the key is checked.
  597. A value pattern is separated from the key pattern with a ``:`` ::
  598. match x:
  599. {}:
  600. print("empty dict")
  601. {"name": "dennis"}:
  602. print("the name is dennis")
  603. {"name": "dennis", "age": var age}:
  604. print("dennis is ", age, " years old.")
  605. {"name", "age"}:
  606. print("has a name and an age, but it's not dennis :(")
  607. {"key": "godotisawesome", ..}:
  608. print("I only checked for one entry and ignored the rest")
  609. Multipatterns:
  610. You can also specify multiple patterns separated by a comma. These patterns aren't allowed to have any bindings in them. ::
  611. match x:
  612. 1, 2, 3:
  613. print("it's 1 - 3")
  614. "sword", "splashpotion", "fist":
  615. print("yep, you've taken damage")
  616. Classes
  617. ~~~~~~~
  618. By default, the body of a script file is an unnamed class and it can
  619. only be referenced externally as a resource or file. Class syntax is
  620. meant to be very compact and can only contain member variables or
  621. functions. Static functions are allowed, but not static members (this is
  622. in the spirit of thread safety, since scripts can be initialized in
  623. separate threads without the user knowing). In the same way, member
  624. variables (including arrays and dictionaries) are initialized every time
  625. an instance is created.
  626. Below is an example of a class file.
  627. ::
  628. # saved as a file named myclass.gd
  629. var a = 5
  630. func print_value_of_a():
  631. print(a)
  632. Inheritance
  633. ^^^^^^^^^^^
  634. A class (stored as a file) can inherit from
  635. - A global class
  636. - Another class file
  637. - An inner class inside another class file.
  638. Multiple inheritance is not allowed.
  639. Inheritance uses the ``extends`` keyword:
  640. ::
  641. # Inherit/extend a globally available class
  642. extends SomeClass
  643. # Inherit/extend a named class file
  644. extends "somefile.gd"
  645. # Inherit/extend an inner class in another file
  646. extends "somefile.gd".SomeInnerClass
  647. To check if a given instance inherits from a given class
  648. the ``extends`` keyword can be used as an operator instead:
  649. ::
  650. # Cache the enemy class
  651. const enemy_class = preload("enemy.gd")
  652. # [...]
  653. # use 'extends' to check inheritance
  654. if (entity extends enemy_class):
  655. entity.apply_damage()
  656. Class Constructor
  657. ^^^^^^^^^^^^^^^^^
  658. The class constructor, called on class instantiation, is named ``_init``.
  659. As mentioned earlier, the constructors of parent classes are called automatically when
  660. inheriting a class. So there is usually no need to call ``._init()`` explicitly.
  661. If a parent constructor takes arguments, they are passed like this:
  662. ::
  663. func _init(args).(parent_args):
  664. pass
  665. Inner classes
  666. ^^^^^^^^^^^^^
  667. A class file can contain inner classes. Inner classes are defined using the
  668. ``class`` keyword. They are instanced using the ``ClassName.new()``
  669. function.
  670. ::
  671. # inside a class file
  672. # An inner class in this class file
  673. class SomeInnerClass:
  674. var a = 5
  675. func print_value_of_a():
  676. print(a)
  677. # This is the constructor of the class file's main class
  678. func _init():
  679. var c = SomeInnerClass.new()
  680. c.print_value_of_a()
  681. Classes as resources
  682. ^^^^^^^^^^^^^^^^^^^^
  683. Classes stored as files are treated as :ref:`resources <class_GDScript>`. They
  684. must be loaded from disk to access them in other classes. This is done using
  685. either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
  686. class resource is done by calling the ``new`` function on the class object::
  687. # Load the class resource when calling load()
  688. var MyClass = load("myclass.gd")
  689. # Preload the class only once at compile time
  690. var MyClass2 = preload("myclass.gd")
  691. func _init():
  692. var a = MyClass.new()
  693. a.somefunction()
  694. Exports
  695. ~~~~~~~
  696. Class members can be exported. This means their value gets saved along
  697. with the resource (e.g. the :ref:`scene <class_PackedScene>`) they're attached
  698. to. They will also be available for editing in the property editor. Exporting
  699. is done by using the ``export`` keyword::
  700. extends Button
  701. export var number = 5 # value will be saved and visible in the property editor
  702. An exported variable must be initialized to a constant expression or have an
  703. export hint in the form of an argument to the export keyword (see below).
  704. One of the fundamental benefits of exporting member variables is to have
  705. them visible and editable in the editor. This way artists and game designers
  706. can modify values that later influence how the program runs. For this, a
  707. special export syntax is provided.
  708. ::
  709. # If the exported value assigns a constant or constant expression,
  710. # the type will be inferred and used in the editor
  711. export var number = 5
  712. # Export can take a basic data type as an argument which will be
  713. # used in the editor
  714. export(int) var number
  715. # Export can also take a resource type to use as a hint
  716. export(Texture) var character_face
  717. export(PackedScene) var scene_file
  718. # Integers and strings hint enumerated values
  719. # Editor will enumerate as 0, 1 and 2
  720. export(int, "Warrior", "Magician", "Thief") var character_class
  721. # Editor will enumerate with string names
  722. export(String, "Rebecca", "Mary", "Leah") var character_name
  723. # Strings as paths
  724. # String is a path to a file
  725. export(String, FILE) var f
  726. # String is a path to a directory
  727. export(String, DIR) var f
  728. # String is a path to a file, custom filter provided as hint
  729. export(String, FILE, "*.txt") var f
  730. # Using paths in the global filesystem is also possible,
  731. # but only in tool scripts (see further below)
  732. # String is a path to a PNG file in the global filesystem
  733. export(String, FILE, GLOBAL, "*.png") var tool_image
  734. # String is a path to a directory in the global filesystem
  735. export(String, DIR, GLOBAL) var tool_dir
  736. # The MULTILINE setting tells the editor to show a large input
  737. # field for editing over multiple lines
  738. export(String, MULTILINE) var text
  739. # Limiting editor input ranges
  740. # Allow integer values from 0 to 20
  741. export(int, 20) var i
  742. # Allow integer values from -10 to 20
  743. export(int, -10, 20) var j
  744. # Allow floats from -10 to 20, with a step of 0.2
  745. export(float, -10, 20, 0.2) var k
  746. # Allow values y = exp(x) where y varies betwee 100 and 1000
  747. # while snapping to steps of 20. The editor will present a
  748. # slider for easily editing the value.
  749. export(float, EXP, 100, 1000, 20) var l
  750. # Floats with easing hint
  751. # Display a visual representation of the ease() function
  752. # when editing
  753. export(float, EASE) var transition_speed
  754. # Colors
  755. # Color given as Red-Green-Blue value
  756. export(Color, RGB) var col # Color is RGB
  757. # Color given as Red-Green-Blue-Alpha value
  758. export(Color, RGBA) var col # Color is RGBA
  759. # another node in the scene can be exported too
  760. export(NodePath) var node
  761. It must be noted that even if the script is not being run while at the
  762. editor, the exported properties are still editable (see below for
  763. "tool").
  764. Exporting bit flags
  765. ^^^^^^^^^^^^^^^^^^^
  766. Integers used as bit flags can store multiple ``true``/``false`` (boolean)
  767. values in one property. By using the export hint ``int, FLAGS``, they
  768. can be set from the editor:
  769. ::
  770. # Individually edit the bits of an integer
  771. export(int, FLAGS) var spell_elements = ELEMENT_WIND | ELEMENT_WATER
  772. Restricting the flags to a certain number of named flags is also
  773. possible. The syntax is very similar to the enumeration syntax:
  774. ::
  775. # Set any of the given flags from the editor
  776. export(int, FLAGS, "Fire", "Water", "Earth", "Wind") var spell_elements = 0
  777. In this example, ``Fire`` has value 1, ``Water`` has value 2, ``Earth``
  778. has value 4 and ``Wind`` corresponds to value 8. Usually, constants
  779. should be defined accordingly (e.g. ``const ELEMENT_WIND = 8`` and so
  780. on).
  781. Using bit flags requires some understanding of bitwise operations. If in
  782. doubt, boolean variables should be exported instead.
  783. Exporting arrays
  784. ^^^^^^^^^^^^^^^^
  785. Exporting arrays works but with an important caveat: While regular
  786. arrays are created local to every class instance, exported arrays are *shared*
  787. between all instances. This means that editing them in one instance will
  788. cause them to change in all other instances. Exported arrays can have
  789. initializers, but they must be constant expressions.
  790. ::
  791. # Exported array, shared between all instances.
  792. # Default value must be a constant expression.
  793. export var a=[1,2,3]
  794. # Typed arrays also work, only initialized empty:
  795. export var vector3s = Vector3Array()
  796. export var strings = StringArray()
  797. # Regular array, created local for every instance.
  798. # Default value can include run-time values, but can't
  799. # be exported.
  800. var b = [a,2,3]
  801. Setters/getters
  802. ~~~~~~~~~~~~~~~
  803. It is often useful to know when a class' member variable changes for
  804. whatever reason. It may also be desired to encapsulate its access in some way.
  805. For this, GDScript provides a *setter/getter* syntax using the ``setget`` keyword.
  806. It is used directly after a variable definition:
  807. ::
  808. var variable = value setget setterfunc, getterfunc
  809. Whenever the value of ``variable`` is modified by an *external* source
  810. (i.e. not from local usage in the class), the *setter* function (``setterfunc`` above)
  811. will be called. This happens *before* the value is changed. The *setter* must decide what to do
  812. with the new value. Vice-versa, when ``variable`` is accessed, the *getter* function
  813. (``getterfunc`` above) must ``return`` the desired value. Below is an example:
  814. ::
  815. var myvar setget myvar_set,myvar_get
  816. func myvar_set(newvalue):
  817. myvar=newvalue
  818. func myvar_get():
  819. return myvar # getter must return a value
  820. Either of the *setter* or *getter* functions can be omitted:
  821. ::
  822. # Only a setter
  823. var myvar = 5 setget myvar_set
  824. # Only a getter (note the comma)
  825. var myvar = 5 setget ,myvar_get
  826. Get/Setters are especially useful when exporting variables to editor in tool
  827. scripts or plugins, for validating input.
  828. As said *local* access will *not* trigger the setter and getter. Here is an
  829. illustration of this:
  830. ::
  831. func _init():
  832. # Does not trigger setter/getter
  833. myinteger=5
  834. print(myinteger)
  835. # Does trigger setter/getter
  836. self.myinteger=5
  837. print(self.myinteger)
  838. Tool mode
  839. ~~~~~~~~~
  840. Scripts, by default, don't run inside the editor and only the exported
  841. properties can be changed. In some cases it is desired that they do run
  842. inside the editor (as long as they don't execute game code or manually
  843. avoid doing so). For this, the ``tool`` keyword exists and must be
  844. placed at the top of the file:
  845. ::
  846. tool
  847. extends Button
  848. func _ready():
  849. print("Hello")
  850. Memory management
  851. ~~~~~~~~~~~~~~~~~
  852. If a class inherits from :ref:`class_Reference`, then instances will be
  853. freed when no longer in use. No garbage collector exists, just simple
  854. reference counting. By default, all classes that don't define
  855. inheritance extend **Reference**. If this is not desired, then a class
  856. must inherit :ref:`class_Object` manually and must call instance.free(). To
  857. avoid reference cycles that can't be freed, a ``weakref`` function is
  858. provided for creating weak references.
  859. Signals
  860. ~~~~~~~
  861. It is often desired to send a notification that something happened in an
  862. instance. GDScript supports creation of built-in Godot signals.
  863. Declaring a signal in GDScript is easy using the `signal` keyword.
  864. ::
  865. # No arguments
  866. signal your_signal_name
  867. # With arguments
  868. signal your_signal_name_with_args(a,b)
  869. These signals, just like regular signals, can be connected in the editor
  870. or from code. Just take the instance of a class where the signal was
  871. declared and connect it to the method of another instance:
  872. ::
  873. func _callback_no_args():
  874. print("Got callback!")
  875. func _callback_args(a,b):
  876. print("Got callback with args! a: ",a," and b: ",b)
  877. func _at_some_func():
  878. instance.connect("your_signal_name",self,"_callback_no_args")
  879. instance.connect("your_signal_name_with_args",self,"_callback_args")
  880. It is also possible to bind arguments to a signal that lacks them with
  881. your custom values:
  882. ::
  883. func _at_some_func():
  884. instance.connect("your_signal_name",self,"_callback_args",[22,"hello"])
  885. This is very useful when a signal from many objects is connected to a
  886. single callback and the sender must be identified:
  887. ::
  888. func _button_pressed(which):
  889. print("Button was pressed: ",which.get_name())
  890. func _ready():
  891. for b in get_node("buttons").get_children():
  892. b.connect("pressed",self,"_button_pressed",[b])
  893. Finally, emitting a custom signal is done by using the
  894. Object.emit_signal method:
  895. ::
  896. func _at_some_func():
  897. emit_signal("your_signal_name")
  898. emit_signal("your_signal_name_with_args",55,128)
  899. someinstance.emit_signal("somesignal")
  900. Coroutines
  901. ~~~~~~~~~~
  902. GDScript offers support for `coroutines <https://en.wikipedia.org/wiki/Coroutine>`_
  903. via the ``yield`` built-in function. Calling ``yield()`` will
  904. immediately return from the current function, with the current frozen
  905. state of the same function as the return value. Calling ``resume`` on
  906. this resulting object will continue execution and return whatever the
  907. function returns. Once resumed the state object becomes invalid. Here is
  908. an example:
  909. ::
  910. func myfunc():
  911. print("hello")
  912. yield()
  913. print("world")
  914. func _ready():
  915. var y = myfunc()
  916. # Function state saved in 'y'
  917. print("my dear")
  918. y.resume()
  919. # 'y' resumed and is now an invalid state
  920. Will print:
  921. ::
  922. hello
  923. my dear
  924. world
  925. It is also possible to pass values between yield() and resume(), for
  926. example:
  927. ::
  928. func myfunc():
  929. print("hello")
  930. print( yield() )
  931. return "cheers!"
  932. func _ready():
  933. var y = myfunc()
  934. # Function state saved in 'y'
  935. print( y.resume("world") )
  936. # 'y' resumed and is now an invalid state
  937. Will print:
  938. ::
  939. hello
  940. world
  941. cheers!
  942. Coroutines & signals
  943. ^^^^^^^^^^^^^^^^^^^^
  944. The real strength of using ``yield`` is when combined with signals.
  945. ``yield`` can accept two parameters, an object and a signal. When the
  946. signal is received, execution will recommence. Here are some examples:
  947. ::
  948. # Resume execution the next frame
  949. yield(get_tree(), "idle_frame")
  950. # Resume execution when animation is done playing:
  951. yield(get_node("AnimationPlayer"), "finished")
  952. # Wait 5 seconds, then resume execution
  953. yield(get_tree().create_timer(5.0), "timeout")
  954. Onready keyword
  955. ~~~~~~~~~~~~~~~
  956. When using nodes, it's very common to desire to keep references to parts
  957. of the scene in a variable. As scenes are only warranted to be
  958. configured when entering the active scene tree, the sub-nodes can only
  959. be obtained when a call to Node._ready() is made.
  960. ::
  961. var mylabel
  962. func _ready():
  963. mylabel = get_node("MyLabel")
  964. This can get a little cumbersome, specially when nodes and external
  965. references pile up. For this, GDScript has the ``onready`` keyword, that
  966. defers initialization of a member variable until _ready is called. It
  967. can replace the above code with a single line:
  968. ::
  969. onready var mylabel = get_node("MyLabel")