gdscript.rst 41 KB

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