gdscript.rst 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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 that is very similar to the Python
  8. language (blocks are indent-based) and its goal is to be very optimal
  9. and tightly integrated with the engine, allowing great flexibility for
  10. content creation and integration.
  11. History
  12. -------
  13. Initially, Godot was designed to support multiple scripting languages
  14. (this ability still exists today). However, only GDScript is in use
  15. right now. There is a little history behind this.
  16. In the early days, the engine used the `Lua <http://www.lua.org>`__
  17. scripting language. Lua is fast, but creating bindings to an object
  18. oriented system (by using fallbacks) was complex and slow and took an
  19. enormous amount of code. After some experiments with
  20. `Python <http://www.python.org>`__, it also proved difficult to embed.
  21. The last third party scripting language that was used for shipped games
  22. was `Squirrel <http://squirrel-lang.org>`__, but it was dropped as well.
  23. At that point, it became evident that Godot would work more optimally by
  24. using a built-in scripting language, as the following barriers were met:
  25. - Godot embeds scripts in nodes, most languages are not designed with
  26. this in mind.
  27. - Godot uses several built-in data types for 2D and 3D math, script
  28. languages do not provide this, and binding them is inefficient.
  29. - Godot uses threads heavily for lifting and initializing data from the
  30. net or disk, script interpreters for common languages are not
  31. friendly to this.
  32. - Godot already has a memory management model for resources, most
  33. script languages provide their own, which resulted in duplicate
  34. effort and bugs.
  35. - Binding code is always messy and results in several failure points,
  36. unexpected bugs and generally low maintainability.
  37. Finally, GDScript was written as a custom solution. The language and
  38. interpreter for it ended up being smaller than the binding code itself
  39. for Lua and Squirrel, and equally as functional. With time, having a
  40. built-in language has proven to be a huge advantage.
  41. Example
  42. -------
  43. Some people can learn better by just taking a look at the syntax, so
  44. here's a simple example of how it looks.
  45. ::
  46. # a file is a class!
  47. # inheritance
  48. extends BaseClass
  49. # member variables
  50. var a = 5
  51. var s = "Hello"
  52. var arr = [1, 2, 3]
  53. var dict = {"key":"value", 2:3}
  54. # constants
  55. const answer = 42
  56. const thename = "Charly"
  57. # built-in vector types
  58. var v2 = Vector2(1, 2)
  59. var v3 = Vector3(1, 2, 3)
  60. # function
  61. func some_function(param1, param2):
  62. var local_var = 5
  63. if param1 < local_var:
  64. print(param1)
  65. elif param2 > 5:
  66. print(param2)
  67. else:
  68. print("fail!")
  69. for i in range(20):
  70. print(i)
  71. while(param2 != 0):
  72. param2 -= 1
  73. var local_var2 = param1+3
  74. return local_var2
  75. # subclass
  76. class Something:
  77. var a = 10
  78. # constructor
  79. func _init():
  80. print("constructed!")
  81. var lv = Something.new()
  82. print(lv.a)
  83. If you have previous experience with statically typed languages such as
  84. C, C++, or C# but never used a dynamically typed one, it is advised you
  85. read this tutorial: :ref:`doc_gdscript_more_efficiently`.
  86. Language
  87. --------
  88. Identifiers
  89. ~~~~~~~~~~~
  90. Any string that restricts itself to alphabetic characters (``a`` to
  91. ``z`` and ``A`` to ``Z``), digits (``0`` to ``9``) and ``_`` qualifies
  92. as an identifier. Additionally, identifiers must not begin with a digit.
  93. Identifiers are case-sensitive (``foo`` is different from ``FOO``).
  94. Keywords
  95. ~~~~~~~~
  96. The following is the list of keywords supported by the language. Since
  97. keywords are reserved words (tokens), they can't be used as identifiers.
  98. Operators
  99. ~~~~~~~~~
  100. The following is the list of supported operators and their precedence
  101. (TODO, change since this was made to reflect python operators)
  102. +---------------------------------------------------------------+-----------------------------------------+
  103. | **Operator** | **Description** |
  104. +---------------------------------------------------------------+-----------------------------------------+
  105. | ``x[index]`` | Subscription, Highest Priority |
  106. +---------------------------------------------------------------+-----------------------------------------+
  107. | ``x.attribute`` | Attribute Reference |
  108. +---------------------------------------------------------------+-----------------------------------------+
  109. | ``extends`` | Instance Type Checker |
  110. +---------------------------------------------------------------+-----------------------------------------+
  111. | ``~`` | Bitwise NOT |
  112. +---------------------------------------------------------------+-----------------------------------------+
  113. | ``-x`` | Negative |
  114. +---------------------------------------------------------------+-----------------------------------------+
  115. | ``*`` ``/`` ``%`` | Multiplication / Division / Remainder |
  116. +---------------------------------------------------------------+-----------------------------------------+
  117. | ``+`` ``-`` | Addition / Subtraction |
  118. +---------------------------------------------------------------+-----------------------------------------+
  119. | ``<<`` ``>>`` | Bit Shifting |
  120. +---------------------------------------------------------------+-----------------------------------------+
  121. | ``&`` | Bitwise AND |
  122. +---------------------------------------------------------------+-----------------------------------------+
  123. | ``^`` | Bitwise XOR |
  124. +---------------------------------------------------------------+-----------------------------------------+
  125. | ``|`` | Bitwise OR |
  126. +---------------------------------------------------------------+-----------------------------------------+
  127. | ``<`` ``>`` ``==`` ``!=`` ``>=`` ``<=`` | Comparisons |
  128. +---------------------------------------------------------------+-----------------------------------------+
  129. | ``in`` | Content Test |
  130. +---------------------------------------------------------------+-----------------------------------------+
  131. | ``!`` ``not`` | Boolean NOT |
  132. +---------------------------------------------------------------+-----------------------------------------+
  133. | ``and`` ``&&`` | Boolean AND |
  134. +---------------------------------------------------------------+-----------------------------------------+
  135. | ``or`` ``||`` | Boolean OR |
  136. +---------------------------------------------------------------+-----------------------------------------+
  137. | ``=`` ``+=`` ``-=`` ``*=`` ``/=`` ``%=`` ``&=`` ``|=`` | Assignment, Lowest Priority |
  138. +---------------------------------------------------------------+-----------------------------------------+
  139. Literals
  140. ~~~~~~~~
  141. +--------------------------+--------------------------------+
  142. | **Literal** | **Type** |
  143. +--------------------------+--------------------------------+
  144. | ``45`` | Base 10 integer |
  145. +--------------------------+--------------------------------+
  146. | ``0x8F51`` | Base 16 (hex) integer |
  147. +--------------------------+--------------------------------+
  148. | ``3.14``, ``58.1e-10`` | Floating point number (real) |
  149. +--------------------------+--------------------------------+
  150. | ``"Hello"``, ``"Hi"`` | Strings |
  151. +--------------------------+--------------------------------+
  152. | ``"""Hello, Dude"""`` | Multiline string |
  153. +--------------------------+--------------------------------+
  154. | ``@"Node/Label"`` | NodePath or StringName |
  155. +--------------------------+--------------------------------+
  156. Comments
  157. ~~~~~~~~
  158. Anything from a ``#`` to the end of the line is ignored and is
  159. considered a comment.
  160. ::
  161. # This is a comment
  162. Multi-line comments can be created using """ (three quotes in a row) at
  163. the beginning and end of a block of text.
  164. ::
  165. """ Everything on these
  166. lines is considered
  167. a comment """
  168. Built-in types
  169. --------------
  170. Basic built-in types
  171. ~~~~~~~~~~~~~~~~~~~~
  172. A variable in GDScript can be assigned to several built-in types.
  173. null
  174. ^^^^
  175. null is a data type that contains no information, nothing assigned, and
  176. it's just empty. It can only be set to one value: ``null``.
  177. bool
  178. ^^^^
  179. The Boolean data type can only contain ``true`` or ``false``.
  180. int
  181. ^^^
  182. The integer data type can only contain integer numbers, (both negative
  183. and positive).
  184. float
  185. ^^^^^
  186. Used to contain a floating point value (real numbers).
  187. :ref:`String <class_String>`
  188. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  189. A sequence of characters in Unicode format. Strings can contain the
  190. standard C escape sequences.
  191. Vector built-in types
  192. ~~~~~~~~~~~~~~~~~~~~~
  193. :ref:`Vector2 <class_Vector2>`
  194. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  195. 2D vector type containing ``x`` and ``y`` fields. Can alternatively
  196. access fields as ``width`` and ``height`` for readability. Can also be
  197. accessed as array.
  198. :ref:`Rect2 <class_Rect2>`
  199. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  200. 2D Rectangle type containing two vectors fields: ``pos`` and ``size``.
  201. Alternatively contains an ``end`` field which is ``pos+size``.
  202. :ref:`Vector3 <class_Vector3>`
  203. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  204. 3D vector type containing ``x``, ``y`` and ``z`` fields. This can also
  205. be accessed as an array.
  206. :ref:`Matrix32 <class_Matrix32>`
  207. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  208. 3x2 matrix used for 2D transforms.
  209. :ref:`Plane <class_Plane>`
  210. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  211. 3D Plane type in normalized form that contains a ``normal`` vector field
  212. and a ``d`` scalar distance.
  213. :ref:`Quat <class_Quat>`
  214. ^^^^^^^^^^^^^^^^^^^^^^^^
  215. Quaternion is a datatype used for representing a 3D rotation. It's
  216. useful for interpolating rotations.
  217. :ref:`AABB <class_AABB>`
  218. ^^^^^^^^^^^^^^^^^^^^^^^^
  219. Axis Aligned bounding box (or 3D box) contains 2 vectors fields: ``pos``
  220. and ``size``. Alternatively contains an ``end`` field which is
  221. ``pos+size``. As an alias of this type, ``Rect3`` can be used
  222. interchangeably.
  223. :ref:`Matrix3 <class_Matrix3>`
  224. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  225. 3x3 matrix used for 3D rotation and scale. It contains 3 vector fields
  226. (``x``, ``y`` and ``z``) and can also be accessed as an array of 3D
  227. vectors.
  228. :ref:`Transform <class_Transform>`
  229. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  230. 3D Transform contains a Matrix3 field ``basis`` and a Vector3 field
  231. ``origin``.
  232. Engine built-in types
  233. ~~~~~~~~~~~~~~~~~~~~~
  234. :ref:`Color <class_Color>`
  235. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  236. Color data type contains ``r``, ``g``, ``b``, and ``a`` fields. It can
  237. also be accessed as ``h``, ``s``, and ``v`` for hue/saturation/value.
  238. :ref:`Image <class_Image>`
  239. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  240. Contains a custom format 2D image and allows direct access to the
  241. pixels.
  242. :ref:`NodePath <class_NodePath>`
  243. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  244. Compiled path to a node used mainly in the scene system. It can be
  245. easily assigned to, and from, a String.
  246. :ref:`RID <class_RID>`
  247. ^^^^^^^^^^^^^^^^^^^^^^
  248. Resource ID (RID). Servers use generic RIDs to reference opaque data.
  249. :ref:`Object <class_Object>`
  250. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  251. Base class for anything that is not a built-in type.
  252. :ref:`InputEvent <class_InputEvent>`
  253. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  254. Events from input devices are contained in very compact form in
  255. InputEvent objects. Due to the fact that they can be received in high
  256. amounts from frame to frame they are optimized as their own data type.
  257. Container built-in types
  258. ~~~~~~~~~~~~~~~~~~~~~~~~
  259. :ref:`Array <class_Array>`
  260. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  261. Generic sequence of objects. Its size can be changed to anything and
  262. starts from index 0.
  263. ::
  264. var arr=[]
  265. arr=[1, 2, 3]
  266. arr[0] = "Hi!"
  267. Arrays are allocated linearly in memory, so they are fast, but very
  268. large arrays (more than tens of thousands of elements) may cause
  269. fragmentation.
  270. There are specialized arrays (listed below) for some built-in data types
  271. which do not suffer from this and use less memory, but they are atomic
  272. and generally run a little slower, so they are only justified for very
  273. large amount of data.
  274. :ref:`Dictionary <class_Dictionary>`
  275. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  276. Associative container which contains values referenced by unique keys.
  277. ::
  278. var d={4:5, "a key":"a value", 28:[1,2,3]}
  279. d["Hi!"] = 0
  280. Lua-style table syntax is also supported, given that it's easier to
  281. write and read:
  282. ::
  283. var d = {
  284. somekey = 2,
  285. otherkey = [2,3,4],
  286. morekey = "Hello"
  287. }
  288. :ref:`ByteArray <class_ByteArray>`
  289. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  290. An array of bytes can only contain bytes (integers from 0 to 255).
  291. This, and all of the following specialized array types, are optimized
  292. for memory usage and can't fragment the memory.
  293. :ref:`IntArray <class_IntArray>`
  294. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  295. Array of integers can only contain integers.
  296. :ref:`FloatArray <class_FloatArray>`
  297. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  298. Array of floats can only contain floats.
  299. :ref:`StringArray <class_StringArray>`
  300. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  301. Array of strings can only contain strings.
  302. :ref:`Vector2Array <class_Vector2Array>`
  303. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  304. Array of Vector2 can only contain 2D Vectors.
  305. :ref:`Vector3Array <class_Vector3Array>`
  306. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  307. Array of Vector3 can only contain 3D Vectors.
  308. :ref:`ColorArray <class_ColorArray>`
  309. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  310. Array of Color can only contains colors.
  311. Data
  312. ----
  313. Variables
  314. ~~~~~~~~~
  315. Variables can exist as class members or local to functions. They are
  316. created with the ``var`` keyword and may, optionally, be assigned a
  317. value upon initialization.
  318. ::
  319. var a # data type is null by default
  320. var b = 5
  321. var c = 3.8
  322. var d = b + c # variables are always initialized in order
  323. Constants
  324. ~~~~~~~~~
  325. Constants are similar to variables, but must be constants or constant
  326. expressions and must be assigned on initialization.
  327. ::
  328. const a = 5
  329. const b = Vector2(20, 20)
  330. const c = 10 + 20 # constant expression
  331. const d = Vector2(20, 30).x # constant expression: 20
  332. const e = [1, 2, 3, 4][0] # constant expression: 1
  333. const f = sin(20) # sin() can be used in constant expressions
  334. const g = x + 20 # invalid; this is not a constant expression!
  335. Functions
  336. ~~~~~~~~~
  337. Functions always belong to a class. The scope priority for variable
  338. look-up is: local→class member→global. ``self`` is provided as an option
  339. for accessing class members, but is not always required (and must *not*
  340. be defined as the first parameter, like in Python). For performance
  341. reasons, functions are not considered class members, so they can't be
  342. referenced directly. A function can return at any point. The default
  343. return value is null.
  344. ::
  345. func myfunction(a, b):
  346. print(a)
  347. print(b)
  348. return a + b # return is optional; without it null is returned
  349. Statements and control flow
  350. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  351. Statements are standard and can be assignments, function calls, control
  352. flow structures, etc (see below). ``;`` as a statement separator is
  353. entirely optional.
  354. if/else/elif
  355. ^^^^^^^^^^^^
  356. Simple conditions are created by using the *if/else/elif* syntax.
  357. Parenthesis around statements is allowed, but not required. Given the
  358. nature of the tab-based indentation, elif can be used instead of
  359. else:/if: to maintain a level of indentation.
  360. ::
  361. if [expression]:
  362. statement(s)
  363. elif [expression]:
  364. statement(s)
  365. else:
  366. statement(s)
  367. while
  368. ^^^^^
  369. Simple loops are created by using *while* syntax. Loops can be broken
  370. using *break* or continued using *continue*:
  371. ::
  372. while [expression]:
  373. statement(s)
  374. for
  375. ^^^
  376. To iterate through a range, such as an array or table, a *for* loop is
  377. used. For loops store the index in the loop variable on each iteration.
  378. ::
  379. for i in [0, 1, 2]:
  380. statement # loop iterates 3 times with i as 0, then 1 and finally 2
  381. var dict = {"a":0, "b":1, "c":2}
  382. for i in dict:
  383. print(dict[i]) # loop iterates the keys; with i being "a","b" and "c" it prints 0, 1 and 2.
  384. for i in range(3):
  385. statement # similar to [0, 1, 2] but does not allocate an array
  386. for i in range(1,3):
  387. statement # similar to [1, 2] but does not allocate an array
  388. for i in range(2,8,2):
  389. statement # similar to [2, 4, 6] but does not allocate an array
  390. Function call on base class
  391. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  392. To call a function on a base class (that was overridden in the current
  393. one), prepend ``.`` to the function name:
  394. ::
  395. .basefunc()
  396. However, remember that functions such as ``_init``, and most
  397. notifications such as ``_enter_tree``, ``_exit_tree``, ``_process``,
  398. ``_fixed_process``, etc. are called in all base classes automatically,
  399. so this should be only for calling functions you write yourself.
  400. Classes
  401. ^^^^^^^
  402. By default, the body of a script file is an unnamed class and it can
  403. only be referenced externally as a resource or file. Class syntax is
  404. meant to be very compact and can only contain member variables or
  405. functions. Static functions are allowed, but not static members (this is
  406. in the spirit of thread safety since scripts can be initialized in
  407. separate threads without the user knowing). In the same way, member
  408. variables (including arrays and dictionaries) are initialized every time
  409. an instance is created.
  410. Class file example
  411. ~~~~~~~~~~~~~~~~~~
  412. Imagine the following being stored in a file like myclass.gd.
  413. ::
  414. var a = 5
  415. func print_value_of_a():
  416. print(a)
  417. Inheritance
  418. ~~~~~~~~~~~
  419. A class file can inherit from a global class, another file or a subclass
  420. inside another file. Multiple inheritance is not allowed. The
  421. ``extends`` syntax is used. Follows is 3 methods of using extends:
  422. ::
  423. # extend from some class (global)
  424. extends SomeClass
  425. ::
  426. # optionally, extend from another file
  427. extends "somefile.gd"
  428. ::
  429. # extend from a subclass in another file
  430. extends "somefile.gd".Subclass
  431. Inheritance testing
  432. ~~~~~~~~~~~~~~~~~~~
  433. It's possible to check if an instance inherits from a given class. For
  434. this the ``extends`` keyword can be used as an operator instead:
  435. ::
  436. const enemy_class = preload("enemy.gd") # cache the enemy class
  437. # [...]
  438. if (entity extends enemy_class):
  439. entity.apply_damage()
  440. Constructor
  441. ~~~~~~~~~~~
  442. A class can have an optional constructor; a function named ``_init``
  443. that is called when the class is instanced.
  444. Arguments to parent constructor
  445. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  446. When inheriting, parent constructors are called automatically (no need
  447. to call ``._init()``). If a parent constructor takes arguments, they are
  448. passed like this:
  449. ::
  450. func _init(args).(parentargs):
  451. pass
  452. Sub classes
  453. ~~~~~~~~~~~
  454. A class file can have subclasses. This syntax should be straightforward:
  455. ::
  456. class SomeSubClass:
  457. var a = 5
  458. func print_value_of_a():
  459. print(a)
  460. func _init():
  461. var sc = SomeSubClass.new() #instance by calling built-in new
  462. sc.print_value_of_a()
  463. Classes as objects
  464. ~~~~~~~~~~~~~~~~~~
  465. It may be desired at some point to load a class from a file and then
  466. instance it. Since the global scope does not exist, classes must be
  467. loaded as a resource. Instancing is done by calling the ``new`` function
  468. in a class object:
  469. ::
  470. # load the class (loaded every time the script is instanced)
  471. var MyClass = load("myclass.gd")
  472. # alternatively, using the preload() function preloads the class at compile time
  473. var MyClass2 = preload("myclass.gd")
  474. func _init():
  475. var a = MyClass.new()
  476. a.somefunction()
  477. Exports
  478. ~~~~~~~
  479. Class members can be exported. This means their value gets saved along
  480. with a scene. If class members have initializers to constant
  481. expressions, they will be available for editing in the property editor.
  482. Exporting is done by using the export keyword:
  483. ::
  484. extends Button
  485. export var data # value will be saved
  486. export var number = 5 # also available to the property editor
  487. One of the fundamental benefits of exporting member variables is to have
  488. them visible in the property editor. This way artists and game designers
  489. can modify values that later influence how the program runs. For this, a
  490. special export syntax is provided for more detail in the exported
  491. variables:
  492. ::
  493. # if the exported value assigns a constant or constant expression, the type will be inferred and used in the editor
  494. export var number = 5
  495. # export can take a basic data type as an argument which will be used in the editor
  496. export(int) var number
  497. # export can also take a resource type to use as a hint
  498. export(Texture) var character_face
  499. # integers and strings hint enumerated values
  500. export(int, "Warrior", "Magician", "Thief") var character_class # (editor will set them as 0, 1 and 2)
  501. export(String, "Rebecca", "Mary", "Leah") var character_name
  502. # strings as paths
  503. export(String, FILE) var f # string is a path to a file
  504. export(String, DIR) var f # string is a path to a directory
  505. export(String, FILE, "*.txt") var f # string is a path to a file, custom filter provided as hint
  506. # using paths in the global filesystem is also possible, but only in tool scripts (see further below)
  507. export(String, FILE, GLOBAL, "*.png") var tool_image # string is a path to a PNG file in the global filesystem
  508. export(String, DIR, GLOBAL) var tool_dir # string is a path to a directory in the global filesystem
  509. # multiline strings
  510. export(String, MULTILINE) var text # display a large window to edit strings with multiple lines
  511. # integers and floats hint ranges
  512. export(int, 20) var i # 0 to 20 allowed
  513. export(int, -10, 20) var j # -10 to 20 allowed
  514. export(float, -10, 20, 0.2) var k # -10 to 20 allowed, with stepping of 0.2
  515. export(float, EXP, 100, 1000, 20) var l # exponential range, editing this property using the slider will set the value exponentially
  516. # floats with easing hint
  517. export(float, EASE) var transition_speed # display a visual representation of the ease() function when editing
  518. # color can hint availability of alpha
  519. export(Color, RGB) var col # Color is RGB
  520. export(Color, RGBA) var col # Color is RGBA
  521. # another node in the scene can be exported too
  522. export(NodePath) var node
  523. It must be noted that even if the script is not being run while at the
  524. editor, the exported properties are still editable (see below for
  525. "tool").
  526. Exporting bit flags
  527. ^^^^^^^^^^^^^^^^^^^
  528. Integers used as bit flags can store multiple true/false (boolean)
  529. values in one property. By using the export hint ``int, FLAGS``, they
  530. can be set from the editor:
  531. ::
  532. export(int, FLAGS) var spell_elements = ELEMENT_WIND | ELEMENT_WATER # individually edit the bits of an integer
  533. Restricting the flags to a certain number of named flags is also
  534. possible. The syntax is very similar to the enumeration syntax:
  535. ::
  536. export(int, FLAGS, "Fire", "Water", "Earth", "Wind") var spell_elements = 0 # set any of the given flags from the editor
  537. In this example, ``Fire`` has value 1, ``Water`` has value 2, ``Earth``
  538. has value 4 and ``Wind`` corresponds to value 8. Usually, constants
  539. should be defined accordingly (e.g. ``const ELEMENT_WIND = 8`` and so
  540. on).
  541. Using bit flags requires some understanding of bitwise operations. If in
  542. doubt, boolean variables should be exported instead.
  543. Exporting arrays
  544. ^^^^^^^^^^^^^^^^
  545. Exporting arrays works too but there is a restriction. While regular
  546. arrays are created local to every instance, exported arrays are shared
  547. between all instances. This means that editing them in one instance will
  548. cause them to change in all other instances. Exported arrays can have
  549. initializers, but they must be constant expressions.
  550. ::
  551. # Exported array, shared between all instances.
  552. # Default value must be a constant expression.
  553. export var a=[1,2,3]
  554. # Typed arrays also work, only initialized empty:
  555. export var vector3s = Vector3Array()
  556. export var strings = StringArray()
  557. # Regular array, created local for every instance.
  558. # Default value can include run-time values, but can't
  559. # be exported.
  560. var b = [a,2,3]
  561. Static functions
  562. ~~~~~~~~~~~~~~~~
  563. A function can be declared static. When a function is static it has no
  564. access to the instance member variables or ``self``. This is mainly
  565. useful to make libraries of helper functions:
  566. ::
  567. static func sum2(a, b):
  568. return a + b
  569. Setters/getters
  570. ~~~~~~~~~~~~~~~
  571. It is often useful to know when an member variable changed. It may
  572. also be desired to encapsulate its access. For this, GDScript provides
  573. a *setter_/_getter* helper using the ``setget`` keyword.
  574. Just add it at the end of the variable definition line like this:
  575. ::
  576. var myinteger = 5 setget myinteger_changed
  577. If the value of ``myinteger`` is modified *externally* (not from local
  578. usage in the class), the *setter* function will be called beforehand.
  579. The *setter* must, then, decide what to do with the new value. The
  580. *setter function* looks like this:
  581. ::
  582. func myinteger_changed(newvalue):
  583. myinteger=newvalue
  584. A *setter* and a *getter* can be used together too, just define both of
  585. them:
  586. ::
  587. var myvar setget myvar_set,myvar_get
  588. func myvar_set(newvalue):
  589. myvar=newvalue
  590. func myvar_get():
  591. return myvar # getter must return a value
  592. Using simply a *getter* is possible too, just skip the setter:
  593. ::
  594. var myvar setget ,myvar_get
  595. This is especially useful when exporting variables to editor in tool
  596. scripts or plugins, for validating input.
  597. Note: As mentioned before, local access will not trigger the setter and
  598. getter. For example:
  599. ::
  600. func _init():
  601. #does not trigger setter/getter
  602. myinteger=5
  603. print(myinteger)
  604. #triggers setter/getter
  605. self.myinteger=5
  606. print(self.myinteger)
  607. Tool mode
  608. ~~~~~~~~~
  609. Scripts, by default, don't run inside the editor and only the exported
  610. properties can be changed. In some cases it is desired that they do run
  611. inside the editor (as long as they don't execute game code or manually
  612. avoid doing so). For this, the ``tool`` keyword exists and must be
  613. placed at the top of the file:
  614. ::
  615. tool
  616. extends Button
  617. func _ready():
  618. print("Hello")
  619. Memory management
  620. ~~~~~~~~~~~~~~~~~
  621. If a class inherits from :ref:`class_Reference`, then instances will be
  622. freed when no longer in use. No garbage collector exists, just simple
  623. reference counting. By default, all classes that don't define
  624. inheritance extend **Reference**. If this is not desired, then a class
  625. must inherit :ref:`class_Object` manually and must call instance.free(). To
  626. avoid reference cycles that can't be freed, a ``weakref`` function is
  627. provided for creating weak references.
  628. Function references
  629. ~~~~~~~~~~~~~~~~~~~
  630. Functions can't be referenced because they are not treated as class
  631. members. There are two alternatives to this, though. The ``call``
  632. function or the ``funcref`` helper.
  633. ::
  634. instance.call("funcname", args) # call a function by name
  635. var fr = funcref(instance, "funcname") # create a function ref
  636. fr.call_func(args)
  637. Signals
  638. ~~~~~~~
  639. It is often desired to send a notification that something happened in an
  640. instance. GDScript supports creation of built-in Godot signals.
  641. Declaring a signal in GDScript is easy, in the body of the class, just
  642. write:
  643. ::
  644. # no arguments
  645. signal your_signal_name
  646. # with arguments
  647. signal your_signal_name_with_args(a,b)
  648. These signals, just like regular signals, can be connected in the editor
  649. or from code. Just take the instance of a class where the signal was
  650. declared and connect it to the method of another instance:
  651. ::
  652. func _callback_no_args():
  653. print("Got callback!")
  654. func _callback_args(a,b):
  655. print("Got callback with args! a: ",a," and b: ",b)
  656. func _at_some_func():
  657. instance.connect("your_signal_name",self,"callback_no_args")
  658. instance.connect("your_signal_name_with_args",self,"callback_args")
  659. It is also possible to bind arguments to a signal that lacks them with
  660. your custom values:
  661. ::
  662. func _at_some_func():
  663. instance.connect("your_signal_name_with_args",self,"callback_no_args",[22,"hello"])
  664. This is very useful when a signal from many objects is connected to a
  665. single callback and the sender must be identified:
  666. ::
  667. func _button_pressed(which):
  668. print("Button was pressed: ",which.get_name())
  669. func _ready():
  670. for b in get_node("buttons").get_children():
  671. b.connect("pressed",self,"_button_pressed",[b])
  672. Finally, emitting a custom signal is done by using the
  673. Object.emit_signal method:
  674. ::
  675. func _at_some_func():
  676. emit_signal("your_signal_name")
  677. emit_signal("your_signal_name_with_args",55,128)
  678. someinstance.emit_signal("somesignal")
  679. Coroutines
  680. ~~~~~~~~~~
  681. GDScript has some support for coroutines via the ``yield`` built-in
  682. function. The way it works is very simple: Calling ``yield()`` will
  683. immediately return from the current function, with the current frozen
  684. state of the same function as the return value. Calling ``resume`` on
  685. this resulting object will continue execution and return whatever the
  686. function returns. Once resumed the state object becomes invalid. Here is
  687. an example:
  688. ::
  689. func myfunc():
  690. print("hello")
  691. yield()
  692. print("world")
  693. func _ready():
  694. var y = myfunc()
  695. #function state saved in 'y'
  696. print("my dear")
  697. y.resume()
  698. # 'y' resumed and is now an invalid state
  699. Will print:
  700. ::
  701. hello
  702. my dear
  703. world
  704. It is also possible to pass values between yield() and resume(), for
  705. example:
  706. ::
  707. func myfunc():
  708. print("hello")
  709. print( yield() )
  710. return "cheers!"
  711. func _ready():
  712. var y = myfunc()
  713. #function state saved in 'y'
  714. print( y.resume("world") )
  715. # 'y' resumed and is now an invalid state
  716. Will print:
  717. ::
  718. hello
  719. world
  720. cheers!
  721. Coroutines & signals
  722. ~~~~~~~~~~~~~~~~~~~~
  723. The real strength of using ``yield`` is when combined with signals.
  724. ``yield`` can accept two parameters, an object and a signal. When the
  725. signal is activated, execution will return. Here are some examples:
  726. ::
  727. #resume execution the next frame
  728. yield( get_tree(), "idle_frame" )
  729. #resume execution when animation is done playing:
  730. yield( get_node("AnimationPlayer"), "finished" )
  731. Onready keyword
  732. ~~~~~~~~~~~~~~~
  733. When using nodes, it's very common to desire to keep references to parts
  734. of the scene in a variable. As scenes are only warranted to be
  735. configured when entering the active scene tree, the sub-nodes can only
  736. be obtained when a call to Node._ready() is made.
  737. ::
  738. var mylabel
  739. func _ready():
  740. mylabel = get_node("MyLabel")
  741. This can get a little cumbersome, specially when nodes and external
  742. references pile up. For this, GDScript has the ``onready`` keyword, that
  743. defers initialization of a member variable until _ready is called. It
  744. can replace the above code with a single line:
  745. ::
  746. onready var mylabel = get_node("MyLabel")