gdscript_styleguide.rst 21 KB

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