gdscript.rst 46 KB

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