gdscript_styleguide.rst 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. .. _doc_gdscript_styleguide:
  2. GDScript style guide
  3. ====================
  4. Description
  5. -----------
  6. This styleguide lists conventions to write elegant GDScript. The goal is
  7. to encourage writing clean, readable code and promote consistency across
  8. projects, discussions, and tutorials. Hopefully, this will also
  9. encourage development of auto-formatting tools.
  10. Since GDScript is close to Python, this guide is inspired by Python's
  11. `PEP 8 <https://www.python.org/dev/peps/pep-0008/>`__ programming
  12. styleguide.
  13. .. note:: Godot's built-in script editor uses a lot of these conventions
  14. by default. Let it help you.
  15. Formatting conventions
  16. ----------------------
  17. * Use line feed (**LF**) characters to break lines, not CRLF or CR. *(editor default)*
  18. * Use one line feed character at the end of each file. *(editor default)*
  19. * Use **UTF-8** encoding without a `byte order mark <https://en.wikipedia.org/wiki/Byte_order_mark>`_. *(editor default)*
  20. * Use **Tabs** instead of spaces for indentation. *(editor default)*
  21. Each indent level should be one greater than the block containing it.
  22. Code structure
  23. --------------
  24. **Good**:
  25. ::
  26. for i in range(10):
  27. print("hello")
  28. **Bad**:
  29. ::
  30. for i in range(10):
  31. print("hello")
  32. for i in range(10):
  33. print("hello")
  34. Use 2 indent levels to distinguish continuation lines from
  35. regular code blocks.
  36. **Good**:
  37. ::
  38. effect.interpolate_property(sprite, "transform/scale",
  39. sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
  40. Tween.TRANS_QUAD, Tween.EASE_OUT)
  41. **Bad**:
  42. ::
  43. effect.interpolate_property(sprite, "transform/scale",
  44. sprite.get_scale(), Vector2(2.0, 2.0), 0.3,
  45. Tween.TRANS_QUAD, Tween.EASE_OUT)
  46. Blank lines
  47. ~~~~~~~~~~~
  48. Surround functions and class definitions with two blank lines:
  49. ::
  50. func heal(amount):
  51. health += amount
  52. health = min(health, max_health)
  53. emit_signal("health_changed", health)
  54. func take_damage(amount, effect=null):
  55. health -= amount
  56. health = max(0, health)
  57. emit_signal("health_changed", health)
  58. Use one blank line inside functions to separate logical sections.
  59. Line length
  60. ~~~~~~~~~~~
  61. Keep individual lines of code under 100 characters.
  62. If you can, try to keep lines under 80 characters. This helps to read the code
  63. on small displays and with two scripts opened side-by-side in an external text
  64. editor. For example, when looking at a differential revision.
  65. One statement per line
  66. ~~~~~~~~~~~~~~~~~~~~~~
  67. Never combine multiple statements on a single line. No, C programmers,
  68. not even with a single line conditional statement.
  69. **Good**:
  70. ::
  71. if position.x > width:
  72. position.x = 0
  73. if flag:
  74. print("flagged")
  75. **Bad**:
  76. ::
  77. if position.x > width: position.x = 0
  78. if flag: print("flagged")
  79. The only exception to that rule is the ternary operator:
  80. ::
  81. next_state = "fall" if not is_on_floor() else "idle"
  82. Avoid unnecessary parentheses
  83. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  84. Avoid parentheses in expressions and conditional statements. Unless
  85. necessary for order of operations, they only reduce readability.
  86. **Good**:
  87. ::
  88. if is_colliding():
  89. queue_free()
  90. **Bad**:
  91. ::
  92. if (is_colliding()):
  93. queue_free()
  94. Boolean operators
  95. ~~~~~~~~~~~~~~~~~
  96. Prefer the plain English versions of boolean operators, as they are the most accessible:
  97. - Use ``and`` instead of ``&&``.
  98. - Use ``or`` instead of ``||``.
  99. You may also use parentheses around boolean operators to clear any ambiguity.
  100. This can make long expressions easier to read.
  101. **Good**:
  102. ::
  103. if (foo and bar) or baz:
  104. print("condition is true")
  105. **Bad**:
  106. ::
  107. if foo && bar || baz:
  108. print("condition is true")
  109. Comment spacing
  110. ~~~~~~~~~~~~~~~
  111. Regular comments should start with a space, but not code that you comment out.
  112. This helps differentiate text comments from disabled code.
  113. **Good**:
  114. ::
  115. # This is a comment.
  116. #print("This is disabled code")
  117. **Bad**:
  118. ::
  119. #This is a comment.
  120. # print("This is disabled code")
  121. .. note::
  122. In the script editor, to toggle the selected code commented, press
  123. <kbd>Ctrl</kbd> <kbd>K</kbd>. This feature adds a single # sign at the start
  124. of the selected lines.
  125. Whitespace
  126. ~~~~~~~~~~
  127. Always use one space around operators and after commas. Also, avoid extra spaces
  128. in dictionary references and function calls.
  129. **Good**:
  130. ::
  131. position.x = 5
  132. position.y = target_position.y + 10
  133. dict["key"] = 5
  134. my_array = [4, 5, 6]
  135. print("foo")
  136. **Bad**:
  137. ::
  138. position.x=5
  139. position.y = mpos.y+10
  140. dict ["key"] = 5
  141. myarray = [4,5,6]
  142. print ("foo")
  143. Don't use spaces to align expressions vertically:
  144. ::
  145. x = 100
  146. y = 100
  147. velocity = 500
  148. Quotes
  149. ~~~~~~
  150. Use double quotes unless single quotes make it possible to escape fewer
  151. characters in a given string. See the examples below:
  152. ::
  153. # Normal string.
  154. print("hello world")
  155. # Use double quotes as usual to avoid escapes.
  156. print("hello 'world'")
  157. # Use single quotes as an exception to the rule to avoid escapes.
  158. print('hello "world"')
  159. # Both quote styles would require 2 escapes; prefer double quotes if it's a tie.
  160. print("'hello' \"world\"")
  161. Naming conventions
  162. ------------------
  163. These naming conventions follow the Godot Engine style. Breaking these
  164. will make your code clash with the built-in naming conventions, which is
  165. ugly.
  166. Classes and nodes
  167. ~~~~~~~~~~~~~~~~~
  168. Use PascalCase for class and node names:
  169. ::
  170. extends KinematicBody
  171. Also use PascalCase when loading a class into a constant or a variable:
  172. ::
  173. const Weapon = preload("res://weapon.gd")
  174. Functions and variables
  175. ~~~~~~~~~~~~~~~~~~~~~~~
  176. Use snake\_case to name functions and variables:
  177. ::
  178. var particle_effect
  179. func load_level():
  180. Prepend a single underscore (\_) to virtual methods functions the user must
  181. override, private functions, and private variables:
  182. ::
  183. var _counter = 0
  184. func _recalculate_path():
  185. Signals
  186. ~~~~~~~
  187. Use the past tense to name signals:
  188. ::
  189. signal door_opened
  190. signal score_changed
  191. Constants and enums
  192. ~~~~~~~~~~~~~~~~~~~
  193. Write constants with CONSTANT\_CASE, that is to say in all caps with an
  194. underscore (\_) to separate words:
  195. ::
  196. const MAX_SPEED = 200
  197. Use PascalCase for enum *names* and CONSTANT\_CASE for their members, as they
  198. are constants:
  199. ::
  200. enum Element {
  201. EARTH,
  202. WATER,
  203. AIR,
  204. FIRE,
  205. }
  206. Static typing
  207. -------------
  208. Since Godot 3.1, GDScript supports :ref:`optional static typing<doc_gdscript_static_typing>`.
  209. Type hints
  210. ~~~~~~~~~~
  211. Place the colon right after the variable's name, without a space, and let the
  212. GDScript compiler infer the variable's type when possible.
  213. **Good**:
  214. ::
  215. onready var health_bar: ProgressBar = get_node("UI/LifeBar")
  216. var health := 0 # The compiler will use the int type
  217. **Bad**:
  218. ::
  219. # The compiler can't infer the exact type and will use Node
  220. # instead of ProgressBar
  221. onready var health_bar := get_node("UI/LifeBar")
  222. When you let the compiler infer the type hint, write the colon and equal signs together: ``:=``.
  223. ::
  224. var health := 0 # The compiler will use the int type
  225. Add a space on either sides of the return type arrow when defining functions.
  226. ::
  227. func heal(amount: int) -> void: