gdscript_styleguide.rst 21 KB

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