gdscript_basics.rst 47 KB

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