gdscript_styleguide.rst 6.8 KB

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