gdscript_basics.rst 43 KB

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