gdscript_styleguide.rst 17 KB

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