gdscript_styleguide.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. .. _doc_gdscript_styleguide:
  2. GDScript style guide
  3. ====================
  4. This style guide lists conventions to write elegant GDScript. The goal is to
  5. encourage writing clean, readable code and promote consistency across projects,
  6. discussions, and tutorials. Hopefully, this will also support the development of
  7. auto-formatting tools.
  8. Since GDScript is close to Python, this guide is inspired by Python's
  9. `PEP 8 <https://www.python.org/dev/peps/pep-0008/>`__ programming
  10. style guide.
  11. Style guides aren't meant as hard rulebooks. At times, you may not be able to
  12. apply some of the guidelines below. When that happens, use your best judgment,
  13. and ask fellow developers for insights.
  14. In general, keeping your code consistent in your projects and within your team is
  15. more important than following this guide to a tee.
  16. .. note:: Godot's built-in script editor uses a lot of these conventions
  17. by default. Let it help you.
  18. Here is a complete class example based on these guidelines:
  19. ::
  20. class_name StateMachine
  21. extends Node
  22. # Hierarchical State machine for the player.
  23. # Initializes states and delegates engine callbacks
  24. # (_physics_process, _unhandled_input) to the state.
  25. signal state_changed(previous, new)
  26. @export var initial_state: Node
  27. var is_active = true:
  28. set = set_is_active
  29. @onready var _state = initial_state:
  30. get = set_state
  31. @onready var _state_name = _state.name
  32. func _init():
  33. add_to_group("state_machine")
  34. func _enter_tree():
  35. print("this happens before the ready method!")
  36. func _ready():
  37. state_changed.connect(_on_state_changed)
  38. _state.enter()
  39. func _unhandled_input(event):
  40. _state.unhandled_input(event)
  41. func _physics_process(delta):
  42. _state.physics_process(delta)
  43. func transition_to(target_state_path, msg={}):
  44. if not has_node(target_state_path):
  45. return
  46. var target_state = get_node(target_state_path)
  47. assert(target_state.is_composite == false)
  48. _state.exit()
  49. self._state = target_state
  50. _state.enter(msg)
  51. Events.player_state_changed.emit(_state.name)
  52. func set_is_active(value):
  53. is_active = value
  54. set_physics_process(value)
  55. set_process_unhandled_input(value)
  56. set_block_signals(not value)
  57. func set_state(value):
  58. _state = value
  59. _state_name = _state.name
  60. func _on_state_changed(previous, new):
  61. print("state changed")
  62. state_changed.emit()
  63. class State:
  64. var foo = 0
  65. func _init():
  66. print("Hello!")
  67. .. _formatting:
  68. Formatting
  69. ----------
  70. Encoding and special characters
  71. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  72. * Use line feed (**LF**) characters to break lines, not CRLF or CR. *(editor default)*
  73. * Use one line feed character at the end of each file. *(editor default)*
  74. * Use **UTF-8** encoding without a `byte order mark <https://en.wikipedia.org/wiki/Byte_order_mark>`_. *(editor default)*
  75. * Use **Tabs** instead of spaces for indentation. *(editor default)*
  76. Indentation
  77. ~~~~~~~~~~~
  78. Each indent level should be one greater than the block containing it.
  79. **Good**:
  80. .. rst-class:: code-example-good
  81. ::
  82. for i in range(10):
  83. print("hello")
  84. **Bad**:
  85. .. rst-class:: code-example-bad
  86. ::
  87. for i in range(10):
  88. print("hello")
  89. for i in range(10):
  90. print("hello")
  91. Use 2 indent levels to distinguish continuation lines from
  92. regular code blocks.
  93. **Good**:
  94. .. rst-class:: code-example-good
  95. ::
  96. effect.interpolate_property(sprite, "transform/scale",
  97. sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
  98. Tween.TRANS_QUAD, Tween.EASE_OUT)
  99. **Bad**:
  100. .. rst-class:: code-example-bad
  101. ::
  102. effect.interpolate_property(sprite, "transform/scale",
  103. sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
  104. Tween.TRANS_QUAD, Tween.EASE_OUT)
  105. Exceptions to this rule are arrays, dictionaries, and enums. Use a single
  106. indentation level to distinguish continuation lines:
  107. **Good**:
  108. .. rst-class:: code-example-good
  109. ::
  110. var party = [
  111. "Godot",
  112. "Godette",
  113. "Steve",
  114. ]
  115. var character_dict = {
  116. "Name": "Bob",
  117. "Age": 27,
  118. "Job": "Mechanic",
  119. }
  120. enum Tiles {
  121. TILE_BRICK,
  122. TILE_FLOOR,
  123. TILE_SPIKE,
  124. TILE_TELEPORT,
  125. }
  126. **Bad**:
  127. .. rst-class:: code-example-bad
  128. ::
  129. var party = [
  130. "Godot",
  131. "Godette",
  132. "Steve",
  133. ]
  134. var character_dict = {
  135. "Name": "Bob",
  136. "Age": 27,
  137. "Job": "Mechanic",
  138. }
  139. enum Tiles {
  140. TILE_BRICK,
  141. TILE_FLOOR,
  142. TILE_SPIKE,
  143. TILE_TELEPORT,
  144. }
  145. Trailing comma
  146. ~~~~~~~~~~~~~~
  147. Use a trailing comma on the last line in arrays, dictionaries, and enums. This
  148. results in easier refactoring and better diffs in version control as the last
  149. line doesn't need to be modified when adding new elements.
  150. **Good**:
  151. .. rst-class:: code-example-good
  152. ::
  153. enum Tiles {
  154. TILE_BRICK,
  155. TILE_FLOOR,
  156. TILE_SPIKE,
  157. TILE_TELEPORT,
  158. }
  159. **Bad**:
  160. .. rst-class:: code-example-bad
  161. ::
  162. enum Tiles {
  163. TILE_BRICK,
  164. TILE_FLOOR,
  165. TILE_SPIKE,
  166. TILE_TELEPORT
  167. }
  168. Trailing commas are unnecessary in single-line lists, so don't add them in this case.
  169. **Good**:
  170. .. rst-class:: code-example-good
  171. ::
  172. enum Tiles {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT}
  173. **Bad**:
  174. .. rst-class:: code-example-bad
  175. ::
  176. enum Tiles {TILE_BRICK, TILE_FLOOR, TILE_SPIKE, TILE_TELEPORT,}
  177. Blank lines
  178. ~~~~~~~~~~~
  179. Surround functions and class definitions with two blank lines:
  180. ::
  181. func heal(amount):
  182. health += amount
  183. health = min(health, max_health)
  184. health_changed.emit(health)
  185. func take_damage(amount, effect=null):
  186. health -= amount
  187. health = max(0, health)
  188. health_changed.emit(health)
  189. Use one blank line inside functions to separate logical sections.
  190. .. note:: We use a single line between classes and function definitions in the class reference and
  191. in short code snippets in this documentation.
  192. Line length
  193. ~~~~~~~~~~~
  194. Keep individual lines of code under 100 characters.
  195. If you can, try to keep lines under 80 characters. This helps to read the code
  196. on small displays and with two scripts opened side-by-side in an external text
  197. editor. For example, when looking at a differential revision.
  198. One statement per line
  199. ~~~~~~~~~~~~~~~~~~~~~~
  200. Never combine multiple statements on a single line. No, C programmers,
  201. not even with a single line conditional statement.
  202. **Good**:
  203. .. rst-class:: code-example-good
  204. ::
  205. if position.x > width:
  206. position.x = 0
  207. if flag:
  208. print("flagged")
  209. **Bad**:
  210. .. rst-class:: code-example-bad
  211. ::
  212. if position.x > width: position.x = 0
  213. if flag: print("flagged")
  214. The only exception to that rule is the ternary operator:
  215. ::
  216. next_state = "idle" if is_on_floor() else "fall"
  217. Format multiline statements for readability
  218. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  219. When you have particularly long ``if`` statements or nested ternary expressions,
  220. wrapping them over multiple lines improves readability. Since continuation lines
  221. are still part of the same expression, 2 indent levels should be used instead of one.
  222. GDScript allows wrapping statements using multiple lines using parentheses or
  223. backslashes. Parentheses are favored in this style guide since they make for
  224. easier refactoring. With backslashes, you have to ensure that the last line
  225. never contains a backslash at the end. With parentheses, you don't have to
  226. worry about the last line having a backslash at the end.
  227. When wrapping a conditional expression over multiple lines, the ``and``/``or``
  228. keywords should be placed at the beginning of the line continuation, not at the
  229. end of the previous line.
  230. **Good**:
  231. .. rst-class:: code-example-good
  232. ::
  233. var angle_degrees = 135
  234. var quadrant = (
  235. "northeast" if angle_degrees <= 90
  236. else "southeast" if angle_degrees <= 180
  237. else "southwest" if angle_degrees <= 270
  238. else "northwest"
  239. )
  240. var position = Vector2(250, 350)
  241. if (
  242. position.x > 200 and position.x < 400
  243. and position.y > 300 and position.y < 400
  244. ):
  245. pass
  246. **Bad**:
  247. .. rst-class:: code-example-bad
  248. ::
  249. var angle_degrees = 135
  250. var quadrant = "northeast" if angle_degrees <= 90 else "southeast" if angle_degrees <= 180 else "southwest" if angle_degrees <= 270 else "northwest"
  251. var position = Vector2(250, 350)
  252. if position.x > 200 and position.x < 400 and position.y > 300 and position.y < 400:
  253. pass
  254. Avoid unnecessary parentheses
  255. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  256. Avoid parentheses in expressions and conditional statements. Unless
  257. necessary for order of operations or wrapping over multiple lines,
  258. they only reduce readability.
  259. **Good**:
  260. .. rst-class:: code-example-good
  261. ::
  262. if is_colliding():
  263. queue_free()
  264. **Bad**:
  265. .. rst-class:: code-example-bad
  266. ::
  267. if (is_colliding()):
  268. queue_free()
  269. .. _boolean_operators:
  270. Boolean operators
  271. ~~~~~~~~~~~~~~~~~
  272. Prefer the plain English versions of boolean operators, as they are the most accessible:
  273. - Use ``and`` instead of ``&&``.
  274. - Use ``or`` instead of ``||``.
  275. - Use ``not`` instead of ``!``.
  276. You may also use parentheses around boolean operators to clear any ambiguity.
  277. This can make long expressions easier to read.
  278. **Good**:
  279. .. rst-class:: code-example-good
  280. ::
  281. if (foo and bar) or not baz:
  282. print("condition is true")
  283. **Bad**:
  284. .. rst-class:: code-example-bad
  285. ::
  286. if foo && bar || !baz:
  287. print("condition is true")
  288. Comment spacing
  289. ~~~~~~~~~~~~~~~
  290. Regular comments should start with a space, but not code that you comment out.
  291. This helps differentiate text comments from disabled code.
  292. **Good**:
  293. .. rst-class:: code-example-good
  294. ::
  295. # This is a comment.
  296. #print("This is disabled code")
  297. **Bad**:
  298. .. rst-class:: code-example-bad
  299. ::
  300. #This is a comment.
  301. # print("This is disabled code")
  302. .. note::
  303. In the script editor, to toggle the selected code commented, press
  304. :kbd:`Ctrl + K`. This feature adds a single # sign at the start
  305. of the selected lines.
  306. Whitespace
  307. ~~~~~~~~~~
  308. Always use one space around operators and after commas. Also, avoid extra spaces
  309. in dictionary references and function calls.
  310. **Good**:
  311. .. rst-class:: code-example-good
  312. ::
  313. position.x = 5
  314. position.y = target_position.y + 10
  315. dict["key"] = 5
  316. my_array = [4, 5, 6]
  317. print("foo")
  318. **Bad**:
  319. .. rst-class:: code-example-bad
  320. ::
  321. position.x=5
  322. position.y = mpos.y+10
  323. dict ["key"] = 5
  324. myarray = [4,5,6]
  325. print ("foo")
  326. Don't use spaces to align expressions vertically:
  327. ::
  328. x = 100
  329. y = 100
  330. velocity = 500
  331. Quotes
  332. ~~~~~~
  333. Use double quotes unless single quotes make it possible to escape fewer
  334. characters in a given string. See the examples below:
  335. ::
  336. # Normal string.
  337. print("hello world")
  338. # Use double quotes as usual to avoid escapes.
  339. print("hello 'world'")
  340. # Use single quotes as an exception to the rule to avoid escapes.
  341. print('hello "world"')
  342. # Both quote styles would require 2 escapes; prefer double quotes if it's a tie.
  343. print("'hello' \"world\"")
  344. Numbers
  345. ~~~~~~~
  346. Don't omit the leading or trailing zero in floating-point numbers. Otherwise,
  347. this makes them less readable and harder to distinguish from integers at a
  348. glance.
  349. **Good**:
  350. .. rst-class:: code-example-good
  351. ::
  352. var float_number = 0.234
  353. var other_float_number = 13.0
  354. **Bad**:
  355. .. rst-class:: code-example-bad
  356. ::
  357. var float_number = .234
  358. var other_float_number = 13.
  359. Use lowercase for letters in hexadecimal numbers, as their lower height makes
  360. the number easier to read.
  361. **Good**:
  362. .. rst-class:: code-example-good
  363. ::
  364. var hex_number = 0xfb8c0b
  365. **Bad**:
  366. .. rst-class:: code-example-bad
  367. ::
  368. var hex_number = 0xFB8C0B
  369. Take advantage of GDScript's underscores in literals to make large numbers more
  370. readable.
  371. **Good**:
  372. .. rst-class:: code-example-good
  373. ::
  374. var large_number = 1_234_567_890
  375. var large_hex_number = 0xffff_f8f8_0000
  376. var large_bin_number = 0b1101_0010_1010
  377. # Numbers lower than 1000000 generally don't need separators.
  378. var small_number = 12345
  379. **Bad**:
  380. .. rst-class:: code-example-bad
  381. ::
  382. var large_number = 1234567890
  383. var large_hex_number = 0xfffff8f80000
  384. var large_bin_number = 0b110100101010
  385. # Numbers lower than 1000000 generally don't need separators.
  386. var small_number = 12_345
  387. .. _naming_conventions:
  388. Naming conventions
  389. ------------------
  390. These naming conventions follow the Godot Engine style. Breaking these will make
  391. your code clash with the built-in naming conventions, leading to inconsistent
  392. code.
  393. File names
  394. ~~~~~~~~~~
  395. Use snake_case for file names. For named classes, convert the PascalCase class
  396. name to snake_case::
  397. # This file should be saved as `weapon.gd`.
  398. class_name Weapon
  399. extends Node
  400. ::
  401. # This file should be saved as `yaml_parser.gd`.
  402. class_name YAMLParser
  403. extends Object
  404. This is consistent with how C++ files are named in Godot's source code. This
  405. also avoids case sensitivity issues that can crop up when exporting a project
  406. from Windows to other platforms.
  407. Classes and nodes
  408. ~~~~~~~~~~~~~~~~~
  409. Use PascalCase for class and node names:
  410. ::
  411. extends CharacterBody3D
  412. Also use PascalCase when loading a class into a constant or a variable:
  413. ::
  414. const Weapon = preload("res://weapon.gd")
  415. Functions and variables
  416. ~~~~~~~~~~~~~~~~~~~~~~~
  417. Use snake\_case to name functions and variables:
  418. ::
  419. var particle_effect
  420. func load_level():
  421. Prepend a single underscore (\_) to virtual methods functions the user must
  422. override, private functions, and private variables:
  423. ::
  424. var _counter = 0
  425. func _recalculate_path():
  426. Signals
  427. ~~~~~~~
  428. Use the past tense to name signals:
  429. ::
  430. signal door_opened
  431. signal score_changed
  432. Constants and enums
  433. ~~~~~~~~~~~~~~~~~~~
  434. Write constants with CONSTANT\_CASE, that is to say in all caps with an
  435. underscore (\_) to separate words:
  436. ::
  437. const MAX_SPEED = 200
  438. Use PascalCase for enum *names* and CONSTANT\_CASE for their members, as they
  439. are constants:
  440. ::
  441. enum Element {
  442. EARTH,
  443. WATER,
  444. AIR,
  445. FIRE,
  446. }
  447. Code order
  448. ----------
  449. This first section focuses on code order. For formatting, see
  450. :ref:`formatting`. For naming conventions, see :ref:`naming_conventions`.
  451. We suggest to organize GDScript code this way:
  452. ::
  453. 01. @tool
  454. 02. class_name
  455. 03. extends
  456. 04. # docstring
  457. 05. signals
  458. 06. enums
  459. 07. constants
  460. 08. @export variables
  461. 09. public variables
  462. 10. private variables
  463. 11. @onready variables
  464. 12. optional built-in virtual _init method
  465. 13. optional built-in virtual _enter_tree() method
  466. 14. built-in virtual _ready method
  467. 15. remaining built-in virtual methods
  468. 16. public methods
  469. 17. private methods
  470. 18. subclasses
  471. We optimized the order to make it easy to read the code from top to bottom, to
  472. help developers reading the code for the first time understand how it works, and
  473. to avoid errors linked to the order of variable declarations.
  474. This code order follows four rules of thumb:
  475. 1. Properties and signals come first, followed by methods.
  476. 2. Public comes before private.
  477. 3. Virtual callbacks come before the class's interface.
  478. 4. The object's construction and initialization functions, ``_init`` and
  479. ``_ready``, come before functions that modify the object at runtime.
  480. Class declaration
  481. ~~~~~~~~~~~~~~~~~
  482. If the code is meant to run in the editor, place the ``@tool`` annotation on the
  483. first line of the script.
  484. Follow with the `class_name` if necessary. You can turn a GDScript file into a
  485. global type in your project using this feature. For more information, see
  486. :ref:`doc_gdscript`.
  487. Then, add the `extends` keyword if the class extends a built-in type.
  488. Following that, you should have the class's optional docstring as comments. You
  489. can use that to explain the role of your class to your teammates, how it works,
  490. and how other developers should use it, for example.
  491. ::
  492. class_name MyNode
  493. extends Node
  494. # A brief description of the class's role and functionality.
  495. # Longer description.
  496. Signals and properties
  497. ~~~~~~~~~~~~~~~~~~~~~~
  498. Write signal declarations, followed by properties, that is to say, member
  499. variables, after the docstring.
  500. Enums should come after signals, as you can use them as export hints for other
  501. properties.
  502. Then, write constants, exported variables, public, private, and onready
  503. variables, in that order.
  504. ::
  505. signal spawn_player(position)
  506. enum Jobs {KNIGHT, WIZARD, ROGUE, HEALER, SHAMAN}
  507. const MAX_LIVES = 3
  508. @export var job: Jobs = Jobs.KNIGHT
  509. @export var max_health = 50
  510. @export var attack = 5
  511. var health = max_health:
  512. set(new_health):
  513. health = new_health
  514. var _speed = 300.0
  515. @onready var sword = get_node("Sword")
  516. @onready var gun = get_node("Gun")
  517. .. note::
  518. The GDScript compiler evaluates onready variables right before the ``_ready``
  519. callback. You can use that to cache node dependencies, that is to say, to get
  520. child nodes in the scene that your class relies on. This is what the example
  521. above shows.
  522. Member variables
  523. ~~~~~~~~~~~~~~~~
  524. Don't declare member variables if they are only used locally in a method, as it
  525. makes the code more difficult to follow. Instead, declare them as local
  526. variables in the method's body.
  527. Local variables
  528. ~~~~~~~~~~~~~~~
  529. Declare local variables as close as possible to their first use. This makes it
  530. easier to follow the code, without having to scroll too much to find where the
  531. variable was declared.
  532. Methods and static functions
  533. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  534. After the class's properties come the methods.
  535. Start with the ``_init()`` callback method, that the engine will call upon
  536. creating the object in memory. Follow with the ``_ready()`` callback, that Godot
  537. calls when it adds a node to the scene tree.
  538. These functions should come first because they show how the object is
  539. initialized.
  540. Other built-in virtual callbacks, like ``_unhandled_input()`` and
  541. ``_physics_process``, should come next. These control the object's main loop and
  542. interactions with the game engine.
  543. The rest of the class's interface, public and private methods, come after that,
  544. in that order.
  545. ::
  546. func _init():
  547. add_to_group("state_machine")
  548. func _ready():
  549. state_changed.connect(_on_state_changed)
  550. _state.enter()
  551. func _unhandled_input(event):
  552. _state.unhandled_input(event)
  553. func transition_to(target_state_path, msg={}):
  554. if not has_node(target_state_path):
  555. return
  556. var target_state = get_node(target_state_path)
  557. assert(target_state.is_composite == false)
  558. _state.exit()
  559. self._state = target_state
  560. _state.enter(msg)
  561. Events.player_state_changed.emit(_state.name)
  562. func _on_state_changed(previous, new):
  563. print("state changed")
  564. state_changed.emit()
  565. Static typing
  566. -------------
  567. Since Godot 3.1, GDScript supports :ref:`optional static typing<doc_gdscript_static_typing>`.
  568. Declared types
  569. ~~~~~~~~~~~~~~
  570. To declare a variable's type, use ``<variable>: <type>``:
  571. ::
  572. var health: int = 0
  573. To declare the return type of a function, use ``-> <type>``:
  574. ::
  575. func heal(amount: int) -> void:
  576. Inferred types
  577. ~~~~~~~~~~~~~~
  578. In most cases you can let the compiler infer the type, using ``:=``.
  579. Prefer ``:=`` when the type is written on the same line as the assignment,
  580. otherwise prefer writing the type explicitly.
  581. **Good**:
  582. .. rst-class:: code-example-good
  583. ::
  584. var health: int = 0 # The type can be int or float, and thus should be stated explicitly.
  585. var direction := Vector3(1, 2, 3) # The type is clearly inferred as Vector3.
  586. Include the type hint when the type is ambiguous, and
  587. omit the type hint when it's redundant.
  588. **Bad**:
  589. .. rst-class:: code-example-bad
  590. ::
  591. var health := 0 # Typed as int, but it could be that float was intended.
  592. var direction: Vector3 = Vector3(1, 2, 3) # The type hint has redundant information.
  593. # What type is this? It's not immediately clear to the reader, so it's bad.
  594. var value := complex_function()
  595. In some cases, the type must be stated explicitly, otherwise the behavior
  596. will not be as expected because the compiler will only be able to use
  597. the function's return type. For example, ``get_node()`` cannot infer a type
  598. unless the scene or file of the node is loaded in memory. In this case, you
  599. should set the type explicitly.
  600. **Good**:
  601. .. rst-class:: code-example-good
  602. ::
  603. @onready var health_bar: ProgressBar = get_node("UI/LifeBar")
  604. Alternatively, you can use the ``as`` keyword to cast the return type, and
  605. that type will be used to infer the type of the var.
  606. .. rst-class:: code-example-good
  607. ::
  608. @onready var health_bar := get_node("UI/LifeBar") as ProgressBar
  609. # health_bar will be typed as ProgressBar
  610. This option is also considered more :ref:`type-safe<doc_gdscript_static_typing_safe_lines>` than the first.
  611. **Bad**:
  612. .. rst-class:: code-example-bad
  613. ::
  614. # The compiler can't infer the exact type and will use Node
  615. # instead of ProgressBar.
  616. @onready var health_bar := get_node("UI/LifeBar")