gdscript_basics.rst 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  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 also be
  272. accessed as array.
  273. :ref:`Rect2 <class_Rect2>`
  274. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  275. 2D Rectangle type containing two vectors fields: ``position`` and ``size``.
  276. Alternatively contains an ``end`` field which is ``position+size``.
  277. :ref:`Vector3 <class_Vector3>`
  278. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  279. 3D vector type containing ``x``, ``y`` and ``z`` fields. This can also
  280. be accessed as an array.
  281. :ref:`Transform2D <class_Transform2D>`
  282. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  283. 3x2 matrix used for 2D transforms.
  284. :ref:`Plane <class_Plane>`
  285. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  286. 3D Plane type in normalized form that contains a ``normal`` vector field
  287. and a ``d`` scalar distance.
  288. :ref:`Quat <class_Quat>`
  289. ^^^^^^^^^^^^^^^^^^^^^^^^
  290. Quaternion is a datatype used for representing a 3D rotation. It's
  291. useful for interpolating rotations.
  292. :ref:`Rect3 <class_Rect3>`
  293. ^^^^^^^^^^^^^^^^^^^^^^^^
  294. Axis Aligned bounding box (or 3D box) contains 2 vectors fields: ``position``
  295. and ``size``. Alternatively contains an ``end`` field which is
  296. ``position+size``.
  297. :ref:`Basis <class_Basis>`
  298. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  299. 3x3 matrix used for 3D rotation and scale. It contains 3 vector fields
  300. (``x``, ``y`` and ``z``) and can also be accessed as an array of 3D
  301. vectors.
  302. :ref:`Transform <class_Transform>`
  303. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  304. 3D Transform contains a Basis field ``basis`` and a Vector3 field
  305. ``origin``.
  306. Engine built-in types
  307. ~~~~~~~~~~~~~~~~~~~~~
  308. :ref:`Color <class_Color>`
  309. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  310. Color data type contains ``r``, ``g``, ``b``, and ``a`` fields. It can
  311. also be accessed as ``h``, ``s``, and ``v`` for hue/saturation/value.
  312. :ref:`NodePath <class_NodePath>`
  313. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  314. Compiled path to a node used mainly in the scene system. It can be
  315. easily assigned to, and from, a String.
  316. :ref:`RID <class_RID>`
  317. ^^^^^^^^^^^^^^^^^^^^^^
  318. Resource ID (RID). Servers use generic RIDs to reference opaque data.
  319. :ref:`Object <class_Object>`
  320. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  321. Base class for anything that is not a built-in type.
  322. Container built-in types
  323. ~~~~~~~~~~~~~~~~~~~~~~~~
  324. :ref:`Array <class_Array>`
  325. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  326. Generic sequence of arbitrary object types, including other arrays or dictionaries (see below).
  327. The array can resize dynamically. Arrays are indexed starting from index ``0``.
  328. Starting with Godot 2.1, indices may be negative like in Python, to count from the end.
  329. ::
  330. var arr=[]
  331. arr=[1, 2, 3]
  332. var b = arr[1] # this is 2
  333. var c = arr[arr.size()-1] # this is 3
  334. var d = arr[-1] # same as the previous line, but shorter
  335. arr[0] = "Hi!" # replacing value 1 with "Hi"
  336. arr.append(4) # array is now ["Hi", 2, 3, 4]
  337. GDScript arrays are allocated linearly in memory for speed. Very
  338. large arrays (more than tens of thousands of elements) may however cause
  339. memory fragmentation. If this is a concern special types of
  340. arrays are available. These only accept a single data type. They avoid memory
  341. fragmentation and also use less memory but are atomic and tend to run slower than generic
  342. arrays. They are therefore only recommended to use for very large data sets:
  343. - :ref:`PoolByteArray <class_PoolByteArray>`: An array of bytes (integers from 0 to 255).
  344. - :ref:`PoolIntArray <class_PoolIntArray>`: An array of integers.
  345. - :ref:`PoolRealArray <class_PoolRealArray>`: An array of floats.
  346. - :ref:`PoolStringArray <class_PoolStringArray>`: An array of strings.
  347. - :ref:`PoolVector2Array <class_PoolVector2Array>`: An array of :ref:`Vector2 <class_Vector2>` objects.
  348. - :ref:`PoolVector3Array <class_PoolVector3Array>`: An array of :ref:`Vector3 <class_Vector3>` objects.
  349. - :ref:`PoolColorArray <class_PoolColorArray>`: An array of :ref:`Color <class_Color>` objects.
  350. :ref:`Dictionary <class_Dictionary>`
  351. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  352. Associative container which contains values referenced by unique keys.
  353. ::
  354. var d={4:5, "a key":"a value", 28:[1,2,3]}
  355. d["Hi!"] = 0
  356. d = {
  357. 22 : "Value",
  358. "somekey" : 2,
  359. "otherkey" : [2,3,4],
  360. "morekey" : "Hello"
  361. }
  362. Lua-style table syntax is also supported. Lua-style uses ``=`` instead of ``:``
  363. and doesn't use quotes to mark string keys (making for slightly less to write).
  364. Note however that like any GDScript identifier, keys written in this form cannot
  365. start with a digit.
  366. ::
  367. var d = {
  368. test22 = "Value",
  369. somekey = 2,
  370. otherkey = [2,3,4],
  371. morekey = "Hello"
  372. }
  373. To add a key to an existing dictionary, access it like an existing key and
  374. assign to it::
  375. var d = {} # create an empty Dictionary
  376. d.Waiting = 14 # add String "Waiting" as a key and assign the value 14 to it
  377. d[4] = "hello" # add integer `4` as a key and assign the String "hello" as its value
  378. d["Godot"] = 3.01 # add String "Godot" as a key and assign the value 3.01 to it
  379. Data
  380. ----
  381. Variables
  382. ~~~~~~~~~
  383. Variables can exist as class members or local to functions. They are
  384. created with the ``var`` keyword and may, optionally, be assigned a
  385. value upon initialization.
  386. ::
  387. var a # data type is null by default
  388. var b = 5
  389. var c = 3.8
  390. var d = b + c # variables are always initialized in order
  391. Constants
  392. ~~~~~~~~~
  393. Constants are similar to variables, but must be constants or constant
  394. expressions and must be assigned on initialization.
  395. ::
  396. const a = 5
  397. const b = Vector2(20, 20)
  398. const c = 10 + 20 # constant expression
  399. const d = Vector2(20, 30).x # constant expression: 20
  400. const e = [1, 2, 3, 4][0] # constant expression: 1
  401. const f = sin(20) # sin() can be used in constant expressions
  402. const g = x + 20 # invalid; this is not a constant expression!
  403. Enums
  404. ^^^^^
  405. Enums are basically a shorthand for constants, and are pretty useful if you
  406. want to assign consecutive integers to some constant.
  407. If you pass a name to the enum, it would also put all the values inside a
  408. constant dictionary of that name.
  409. ::
  410. enum {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  411. # Is the same as:
  412. const TILE_BRICK = 0
  413. const TILE_FLOOR = 1
  414. const TILE_SPIKE = 2
  415. const TILE_TELEPORT = 3
  416. enum State {STATE_IDLE, STATE_JUMP = 5, STATE_SHOOT}
  417. # Is the same as:
  418. const STATE_IDLE = 0
  419. const STATE_JUMP = 5
  420. const STATE_SHOOT = 6
  421. const State = {STATE_IDLE = 0, STATE_JUMP = 5, STATE_SHOOT = 6}
  422. Functions
  423. ~~~~~~~~~
  424. Functions always belong to a `class <Classes_>`_. The scope priority for
  425. variable look-up is: local → class member → global. The ``self`` variable is
  426. always available and is provided as an option for accessing class members, but
  427. is not always required (and should *not* be sent as the function's first
  428. argument, unlike Python).
  429. ::
  430. func myfunction(a, b):
  431. print(a)
  432. print(b)
  433. return a + b # return is optional; without it null is returned
  434. A function can ``return`` at any point. The default return value is ``null``.
  435. Referencing Functions
  436. ^^^^^^^^^^^^^^^^^^^^^
  437. To call a function in a *base class* (i.e. one ``extend``-ed in your current class),
  438. prepend ``.`` to the function name:
  439. ::
  440. .basefunc(args)
  441. Contrary to Python, functions are *not* first class objects in GDScript. This
  442. means they cannot be stored in variables, passed as an argument to another
  443. function or be returned from other functions. This is for performance reasons.
  444. To reference a function by name at runtime, (e.g. to store it in a variable, or
  445. pass it to another function as an argument) one must use the ``call`` or
  446. ``funcref`` helpers::
  447. # Call a function by name in one step
  448. mynode.call("myfunction", args)
  449. # Store a function reference
  450. var myfunc = funcref(mynode, "myfunction")
  451. # Call stored function reference
  452. myfunc.call_func(args)
  453. Remember that default functions like ``_init``, and most
  454. notifications such as ``_enter_tree``, ``_exit_tree``, ``_process``,
  455. ``_fixed_process``, etc. are called in all base classes automatically.
  456. So there is only a need to call the function explicitly when overloading
  457. them in some way.
  458. Static functions
  459. ^^^^^^^^^^^^^^^^
  460. A function can be declared static. When a function is static it has no
  461. access to the instance member variables or ``self``. This is mainly
  462. useful to make libraries of helper functions:
  463. ::
  464. static func sum2(a, b):
  465. return a + b
  466. Statements and control flow
  467. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  468. Statements are standard and can be assignments, function calls, control
  469. flow structures, etc (see below). ``;`` as a statement separator is
  470. entirely optional.
  471. if/else/elif
  472. ^^^^^^^^^^^^
  473. Simple conditions are created by using the ``if``/``else``/``elif`` syntax.
  474. Parenthesis around conditions are allowed, but not required. Given the
  475. nature of the tab-based indentation, ``elif`` can be used instead of
  476. ``else``/``if`` to maintain a level of indentation.
  477. ::
  478. if [expression]:
  479. statement(s)
  480. elif [expression]:
  481. statement(s)
  482. else:
  483. statement(s)
  484. Short statements can be written on the same line as the condition::
  485. if (1 + 1 == 2): return 2 + 2
  486. else:
  487. var x = 3 + 3
  488. return x
  489. Sometimes you might want to assign a different initial value based on a
  490. boolean expression. In this case ternary-if expressions come in handy::
  491. var x = [true-value] if [expression] else [false-value]
  492. y += 3 if y < 10 else -1
  493. while
  494. ^^^^^
  495. Simple loops are created by using ``while`` syntax. Loops can be broken
  496. using ``break`` or continued using ``continue``:
  497. ::
  498. while [expression]:
  499. statement(s)
  500. for
  501. ^^^
  502. To iterate through a range, such as an array or table, a *for* loop is
  503. used. When iterating over an array, the current array element is stored in
  504. the loop variable. When iterating over a dictionary, the *index* is stored
  505. in the loop variable.
  506. ::
  507. for x in [5, 7, 11]:
  508. statement # loop iterates 3 times with x as 5, then 7 and finally 11
  509. var dict = {"a":0, "b":1, "c":2}
  510. for i in dict:
  511. print(dict[i]) # loop provides the keys in an arbitrary order; may print 0, 1, 2, or 2, 0, 1, etc...
  512. for i in range(3):
  513. statement # similar to [0, 1, 2] but does not allocate an array
  514. for i in range(1,3):
  515. statement # similar to [1, 2] but does not allocate an array
  516. for i in range(2,8,2):
  517. statement # similar to [2, 4, 6] but does not allocate an array
  518. for c in "Hello":
  519. print(c) # iterate through all characters in a String, print every letter on new line
  520. match
  521. ^^^^^
  522. A ``match`` statement is used to branch execution of a program.
  523. It's the equivalent of the ``switch`` statement found in many other languages but offers some additional features.
  524. Basic syntax:
  525. ::
  526. match [expression]:
  527. [pattern](s): [block]
  528. [pattern](s): [block]
  529. [pattern](s): [block]
  530. **Crash-course for people who are familiar to switch statements**:
  531. 1. Replace ``switch`` with ``match``
  532. 2. Remove ``case``
  533. 3. Remove any ``break``'s. If you don't want to ``break`` by default you can use ``continue`` for a fallthrough.
  534. 4. Change ``default`` to a single underscore.
  535. **Control flow**:
  536. The patterns are matched from top to bottom.
  537. If a pattern matches, the corresponding block will be executed. After that, the execution continues below the ``match`` statement.
  538. If you want to have a fallthrough you can use ``continue`` to stop execution in the current block and check the ones below it.
  539. There are 6 pattern types:
  540. - constant pattern
  541. constant primitives, like numbers and strings ::
  542. match x:
  543. 1: print("We are number one!")
  544. 2: print("Two are better than one!")
  545. "test": print("Oh snap! It's a string!")
  546. - variable pattern
  547. matches the contents of a variable/enum ::
  548. match typeof(x):
  549. TYPE_FLOAT: print("float")
  550. TYPE_STRING: print("text")
  551. TYPE_ARRAY: print("array")
  552. - wildcard pattern
  553. This pattern matches everything. It's written as a single underscore.
  554. It can be used as the equivalent of the ``default`` in a ``switch`` statement in other languages. ::
  555. match x:
  556. 1: print("it's one!")
  557. 2: print("it's one times two!")
  558. _: print("it's not 1 or 2. I don't care tbh.")
  559. - binding pattern
  560. A binding pattern introduces a new variable. Like the wildcard pattern, it matches everything - and also gives that value a name.
  561. It's especially useful in array and dictionary patterns. ::
  562. match x:
  563. 1: print("it's one!")
  564. 2: print("it's one times two!")
  565. var new_var: print("it's not 1 or 2, it's ", new_var)
  566. - array pattern
  567. matches an array. Every single element of the array pattern is a pattern itself so you can nest them.
  568. The length of the array is tested first, it has to be the same size as the pattern, otherwise the pattern don't match.
  569. **Open-ended array**: An array can be bigger than the pattern by making the last subpattern ``..``
  570. Every subpattern has to be comma separated. ::
  571. match x:
  572. []:
  573. print("empty array")
  574. [1, 3, "test", null]:
  575. print("very specific array")
  576. [var start, _, "test"]:
  577. print("first element is ", start, ", and the last is \"test\"")
  578. [42, ..]:
  579. print("open ended array")
  580. - dictionary pattern
  581. Works in the same was as the array pattern. Every key has to be a constant pattern.
  582. The size of the dictionary is tested first, it has to be the same size as the pattern, otherwise the pattern don't match.
  583. **Open-ended dictionary**: A dictionary can be bigger than the pattern by making the last subpattern ``..``
  584. Every subpattern has to be comma separated.
  585. If you don't specify a value, then only the existence of the key is checked.
  586. A value pattern is separated from the key pattern with a ``:`` ::
  587. match x:
  588. {}:
  589. print("empty dict")
  590. {"name": "dennis"}:
  591. print("the name is dennis")
  592. {"name": "dennis", "age": var age}:
  593. print("dennis is ", age, " years old.")
  594. {"name", "age"}:
  595. print("has a name and an age, but it's not dennis :(")
  596. {"key": "godotisawesome", ..}:
  597. print("I only checked for one entry and ignored the rest")
  598. Multipatterns:
  599. You can also specify multiple patterns separated by a comma. These patterns aren't allowed to have any bindings in them. ::
  600. match x:
  601. 1, 2, 3:
  602. print("it's 1 - 3")
  603. "sword", "splashpotion", "fist":
  604. print("yep, you've taken damage")
  605. Classes
  606. ~~~~~~~
  607. By default, the body of a script file is an unnamed class and it can
  608. only be referenced externally as a resource or file. Class syntax is
  609. meant to be very compact and can only contain member variables or
  610. functions. Static functions are allowed, but not static members (this is
  611. in the spirit of thread safety, since scripts can be initialized in
  612. separate threads without the user knowing). In the same way, member
  613. variables (including arrays and dictionaries) are initialized every time
  614. an instance is created.
  615. Below is an example of a class file.
  616. ::
  617. # saved as a file named myclass.gd
  618. var a = 5
  619. func print_value_of_a():
  620. print(a)
  621. Inheritance
  622. ^^^^^^^^^^^
  623. A class (stored as a file) can inherit from
  624. - A global class
  625. - Another class file
  626. - An inner class inside another class file.
  627. Multiple inheritance is not allowed.
  628. Inheritance uses the ``extends`` keyword:
  629. ::
  630. # Inherit/extend a globally available class
  631. extends SomeClass
  632. # Inherit/extend a named class file
  633. extends "somefile.gd"
  634. # Inherit/extend an inner class in another file
  635. extends "somefile.gd".SomeInnerClass
  636. To check if a given instance inherits from a given class
  637. the ``extends`` keyword can be used as an operator instead:
  638. ::
  639. # Cache the enemy class
  640. const enemy_class = preload("enemy.gd")
  641. # [...]
  642. # use 'extends' to check inheritance
  643. if (entity extends enemy_class):
  644. entity.apply_damage()
  645. Class Constructor
  646. ^^^^^^^^^^^^^^^^^
  647. The class constructor, called on class instantiation, is named ``_init``.
  648. As mentioned earlier, the constructors of parent classes are called automatically when
  649. inheriting a class. So there is usually no need to call ``._init()`` explicitly.
  650. If a parent constructor takes arguments, they are passed like this:
  651. ::
  652. func _init(args).(parent_args):
  653. pass
  654. Inner classes
  655. ^^^^^^^^^^^^^
  656. A class file can contain inner classes. Inner classes are defined using the
  657. ``class`` keyword. They are instanced using the ``ClassName.new()``
  658. function.
  659. ::
  660. # inside a class file
  661. # An inner class in this class file
  662. class SomeInnerClass:
  663. var a = 5
  664. func print_value_of_a():
  665. print(a)
  666. # This is the constructor of the class file's main class
  667. func _init():
  668. var c = SomeInnerClass.new()
  669. c.print_value_of_a()
  670. Classes as resources
  671. ^^^^^^^^^^^^^^^^^^^^
  672. Classes stored as files are treated as :ref:`resources <class_GDScript>`. They
  673. must be loaded from disk to access them in other classes. This is done using
  674. either the ``load`` or ``preload`` functions (see below). Instancing of a loaded
  675. class resource is done by calling the ``new`` function on the class object::
  676. # Load the class resource when calling load()
  677. var MyClass = load("myclass.gd")
  678. # Preload the class only once at compile time
  679. var MyClass2 = preload("myclass.gd")
  680. func _init():
  681. var a = MyClass.new()
  682. a.somefunction()
  683. Exports
  684. ~~~~~~~
  685. Class members can be exported. This means their value gets saved along
  686. with the resource (e.g. the :ref:`scene <class_PackedScene>`) they're attached
  687. to. They will also be available for editing in the property editor. Exporting
  688. is done by using the ``export`` keyword::
  689. extends Button
  690. export var number = 5 # value will be saved and visible in the property editor
  691. An exported variable must be initialized to a constant expression or have an
  692. export hint in the form of an argument to the export keyword (see below).
  693. One of the fundamental benefits of exporting member variables is to have
  694. them visible and editable in the editor. This way artists and game designers
  695. can modify values that later influence how the program runs. For this, a
  696. special export syntax is provided.
  697. ::
  698. # If the exported value assigns a constant or constant expression,
  699. # the type will be inferred and used in the editor
  700. export var number = 5
  701. # Export can take a basic data type as an argument which will be
  702. # used in the editor
  703. export(int) var number
  704. # Export can also take a resource type to use as a hint
  705. export(Texture) var character_face
  706. export(PackedScene) var scene_file
  707. # Integers and strings hint enumerated values
  708. # Editor will enumerate as 0, 1 and 2
  709. export(int, "Warrior", "Magician", "Thief") var character_class
  710. # Editor will enumerate with string names
  711. export(String, "Rebecca", "Mary", "Leah") var character_name
  712. # Strings as paths
  713. # String is a path to a file
  714. export(String, FILE) var f
  715. # String is a path to a directory
  716. export(String, DIR) var f
  717. # String is a path to a file, custom filter provided as hint
  718. export(String, FILE, "*.txt") var f
  719. # Using paths in the global filesystem is also possible,
  720. # but only in tool scripts (see further below)
  721. # String is a path to a PNG file in the global filesystem
  722. export(String, FILE, GLOBAL, "*.png") var tool_image
  723. # String is a path to a directory in the global filesystem
  724. export(String, DIR, GLOBAL) var tool_dir
  725. # The MULTILINE setting tells the editor to show a large input
  726. # field for editing over multiple lines
  727. export(String, MULTILINE) var text
  728. # Limiting editor input ranges
  729. # Allow integer values from 0 to 20
  730. export(int, 20) var i
  731. # Allow integer values from -10 to 20
  732. export(int, -10, 20) var j
  733. # Allow floats from -10 to 20, with a step of 0.2
  734. export(float, -10, 20, 0.2) var k
  735. # Allow values y = exp(x) where y varies betwee 100 and 1000
  736. # while snapping to steps of 20. The editor will present a
  737. # slider for easily editing the value.
  738. export(float, EXP, 100, 1000, 20) var l
  739. # Floats with easing hint
  740. # Display a visual representation of the ease() function
  741. # when editing
  742. export(float, EASE) var transition_speed
  743. # Colors
  744. # Color given as Red-Green-Blue value
  745. export(Color, RGB) var col # Color is RGB
  746. # Color given as Red-Green-Blue-Alpha value
  747. export(Color, RGBA) var col # Color is RGBA
  748. # another node in the scene can be exported too
  749. export(NodePath) var node
  750. It must be noted that even if the script is not being run while at the
  751. editor, the exported properties are still editable (see below for
  752. "tool").
  753. Exporting bit flags
  754. ^^^^^^^^^^^^^^^^^^^
  755. Integers used as bit flags can store multiple ``true``/``false`` (boolean)
  756. values in one property. By using the export hint ``int, FLAGS``, they
  757. can be set from the editor:
  758. ::
  759. # Individually edit the bits of an integer
  760. export(int, FLAGS) var spell_elements = ELEMENT_WIND | ELEMENT_WATER
  761. Restricting the flags to a certain number of named flags is also
  762. possible. The syntax is very similar to the enumeration syntax:
  763. ::
  764. # Set any of the given flags from the editor
  765. export(int, FLAGS, "Fire", "Water", "Earth", "Wind") var spell_elements = 0
  766. In this example, ``Fire`` has value 1, ``Water`` has value 2, ``Earth``
  767. has value 4 and ``Wind`` corresponds to value 8. Usually, constants
  768. should be defined accordingly (e.g. ``const ELEMENT_WIND = 8`` and so
  769. on).
  770. Using bit flags requires some understanding of bitwise operations. If in
  771. doubt, boolean variables should be exported instead.
  772. Exporting arrays
  773. ^^^^^^^^^^^^^^^^
  774. Exporting arrays works but with an important caveat: While regular
  775. arrays are created local to every class instance, exported arrays are *shared*
  776. between all instances. This means that editing them in one instance will
  777. cause them to change in all other instances. Exported arrays can have
  778. initializers, but they must be constant expressions.
  779. ::
  780. # Exported array, shared between all instances.
  781. # Default value must be a constant expression.
  782. export var a=[1,2,3]
  783. # Typed arrays also work, only initialized empty:
  784. export var vector3s = PoolVector3Array()
  785. export var strings = PoolStringArray()
  786. # Regular array, created local for every instance.
  787. # Default value can include run-time values, but can't
  788. # be exported.
  789. var b = [a,2,3]
  790. Setters/getters
  791. ~~~~~~~~~~~~~~~
  792. It is often useful to know when a class' member variable changes for
  793. whatever reason. It may also be desired to encapsulate its access in some way.
  794. For this, GDScript provides a *setter/getter* syntax using the ``setget`` keyword.
  795. It is used directly after a variable definition:
  796. ::
  797. var variable = value setget setterfunc, getterfunc
  798. Whenever the value of ``variable`` is modified by an *external* source
  799. (i.e. not from local usage in the class), the *setter* function (``setterfunc`` above)
  800. will be called. This happens *before* the value is changed. The *setter* must decide what to do
  801. with the new value. Vice-versa, when ``variable`` is accessed, the *getter* function
  802. (``getterfunc`` above) must ``return`` the desired value. Below is an example:
  803. ::
  804. var myvar setget myvar_set,myvar_get
  805. func myvar_set(newvalue):
  806. myvar=newvalue
  807. func myvar_get():
  808. return myvar # getter must return a value
  809. Either of the *setter* or *getter* functions can be omitted:
  810. ::
  811. # Only a setter
  812. var myvar = 5 setget myvar_set
  813. # Only a getter (note the comma)
  814. var myvar = 5 setget ,myvar_get
  815. Get/Setters are especially useful when exporting variables to editor in tool
  816. scripts or plugins, for validating input.
  817. As said *local* access will *not* trigger the setter and getter. Here is an
  818. illustration of this:
  819. ::
  820. func _init():
  821. # Does not trigger setter/getter
  822. myinteger=5
  823. print(myinteger)
  824. # Does trigger setter/getter
  825. self.myinteger=5
  826. print(self.myinteger)
  827. Tool mode
  828. ~~~~~~~~~
  829. Scripts, by default, don't run inside the editor and only the exported
  830. properties can be changed. In some cases it is desired that they do run
  831. inside the editor (as long as they don't execute game code or manually
  832. avoid doing so). For this, the ``tool`` keyword exists and must be
  833. placed at the top of the file:
  834. ::
  835. tool
  836. extends Button
  837. func _ready():
  838. print("Hello")
  839. Memory management
  840. ~~~~~~~~~~~~~~~~~
  841. If a class inherits from :ref:`class_Reference`, then instances will be
  842. freed when no longer in use. No garbage collector exists, just simple
  843. reference counting. By default, all classes that don't define
  844. inheritance extend **Reference**. If this is not desired, then a class
  845. must inherit :ref:`class_Object` manually and must call instance.free(). To
  846. avoid reference cycles that can't be freed, a ``weakref`` function is
  847. provided for creating weak references.
  848. Signals
  849. ~~~~~~~
  850. It is often desired to send a notification that something happened in an
  851. instance. GDScript supports creation of built-in Godot signals.
  852. Declaring a signal in GDScript is easy using the `signal` keyword.
  853. ::
  854. # No arguments
  855. signal your_signal_name
  856. # With arguments
  857. signal your_signal_name_with_args(a,b)
  858. These signals, just like regular signals, can be connected in the editor
  859. or from code. Just take the instance of a class where the signal was
  860. declared and connect it to the method of another instance:
  861. ::
  862. func _callback_no_args():
  863. print("Got callback!")
  864. func _callback_args(a,b):
  865. print("Got callback with args! a: ",a," and b: ",b)
  866. func _at_some_func():
  867. instance.connect("your_signal_name",self,"_callback_no_args")
  868. instance.connect("your_signal_name_with_args",self,"_callback_args")
  869. It is also possible to bind arguments to a signal that lacks them with
  870. your custom values:
  871. ::
  872. func _at_some_func():
  873. instance.connect("your_signal_name",self,"_callback_args",[22,"hello"])
  874. This is very useful when a signal from many objects is connected to a
  875. single callback and the sender must be identified:
  876. ::
  877. func _button_pressed(which):
  878. print("Button was pressed: ",which.get_name())
  879. func _ready():
  880. for b in get_node("buttons").get_children():
  881. b.connect("pressed",self,"_button_pressed",[b])
  882. Finally, emitting a custom signal is done by using the
  883. Object.emit_signal method:
  884. ::
  885. func _at_some_func():
  886. emit_signal("your_signal_name")
  887. emit_signal("your_signal_name_with_args",55,128)
  888. someinstance.emit_signal("somesignal")
  889. Coroutines
  890. ~~~~~~~~~~
  891. GDScript offers support for `coroutines <https://en.wikipedia.org/wiki/Coroutine>`_
  892. via the ``yield`` built-in function. Calling ``yield()`` will
  893. immediately return from the current function, with the current frozen
  894. state of the same function as the return value. Calling ``resume`` on
  895. this resulting object will continue execution and return whatever the
  896. function returns. Once resumed the state object becomes invalid. Here is
  897. an example:
  898. ::
  899. func myfunc():
  900. print("hello")
  901. yield()
  902. print("world")
  903. func _ready():
  904. var y = myfunc()
  905. # Function state saved in 'y'
  906. print("my dear")
  907. y.resume()
  908. # 'y' resumed and is now an invalid state
  909. Will print:
  910. ::
  911. hello
  912. my dear
  913. world
  914. It is also possible to pass values between yield() and resume(), for
  915. example:
  916. ::
  917. func myfunc():
  918. print("hello")
  919. print( yield() )
  920. return "cheers!"
  921. func _ready():
  922. var y = myfunc()
  923. # Function state saved in 'y'
  924. print( y.resume("world") )
  925. # 'y' resumed and is now an invalid state
  926. Will print:
  927. ::
  928. hello
  929. world
  930. cheers!
  931. Coroutines & signals
  932. ^^^^^^^^^^^^^^^^^^^^
  933. The real strength of using ``yield`` is when combined with signals.
  934. ``yield`` can accept two parameters, an object and a signal. When the
  935. signal is received, execution will recommence. Here are some examples:
  936. ::
  937. # Resume execution the next frame
  938. yield(get_tree(), "idle_frame")
  939. # Resume execution when animation is done playing:
  940. yield(get_node("AnimationPlayer"), "finished")
  941. # Wait 5 seconds, then resume execution
  942. yield(get_tree().create_timer(5.0), "timeout")
  943. Onready keyword
  944. ~~~~~~~~~~~~~~~
  945. When using nodes, it's very common to desire to keep references to parts
  946. of the scene in a variable. As scenes are only warranted to be
  947. configured when entering the active scene tree, the sub-nodes can only
  948. be obtained when a call to Node._ready() is made.
  949. ::
  950. var mylabel
  951. func _ready():
  952. mylabel = get_node("MyLabel")
  953. This can get a little cumbersome, specially when nodes and external
  954. references pile up. For this, GDScript has the ``onready`` keyword, that
  955. defers initialization of a member variable until _ready is called. It
  956. can replace the above code with a single line:
  957. ::
  958. onready var mylabel = get_node("MyLabel")