gdscript_styleguide.rst 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. One statement per line
  58. ~~~~~~~~~~~~~~~~~~~~~~
  59. Never combine multiple statements on a single line. No, C programmers,
  60. not with a single line conditional statement (except with the ternary
  61. operator)!
  62. **Good**:
  63. ::
  64. if position.x > width:
  65. position.x = 0
  66. if flag:
  67. print("flagged")
  68. **Bad**:
  69. ::
  70. if position.x > width: position.x = 0
  71. if flag: print("flagged")
  72. Avoid unnecessary parentheses
  73. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  74. Avoid parentheses in expressions and conditional statements. Unless
  75. necessary for order of operations, they only reduce readability.
  76. **Good**:
  77. ::
  78. if is_colliding():
  79. queue_free()
  80. **Bad**:
  81. ::
  82. if (is_colliding()):
  83. queue_free()
  84. Boolean operators
  85. ~~~~~~~~~~~~~~~~~
  86. Prefer the spelled-out versions of boolean operators (``and``/``or``) to their
  87. symbolic equivalents (`&&`/`||`). They're usually more readable as they're plain
  88. English words.
  89. Add parentheses around boolean operators to avoid ambiguity, even if they're not
  90. strictly required. This makes long expressions easier to read.
  91. **Good**:
  92. ::
  93. if (foo and bar) or baz:
  94. print("condition is true")
  95. **Bad**:
  96. ::
  97. if foo && bar || baz:
  98. print("condition is true")
  99. Comment spacing
  100. ~~~~~~~~~~~~~~~
  101. Normal comments should start with a space, but comments which are disabled
  102. code should not. This helps differentiate text comments from disabled code.
  103. **Good**:
  104. ::
  105. # This is a comment.
  106. #print("This is disabled code")
  107. **Bad**:
  108. ::
  109. #This is a comment.
  110. # print("This is disabled code")
  111. Whitespace
  112. ~~~~~~~~~~
  113. Always use one space around operators and after commas. Avoid extra
  114. spaces in dictionary references and function calls, or to create "columns."
  115. **Good**:
  116. ::
  117. position.x = 5
  118. position.y = mpos.y + 10
  119. dict["key"] = 5
  120. myarray = [4, 5, 6]
  121. print("foo")
  122. **Bad**:
  123. ::
  124. position.x=5
  125. position.y = mpos.y+10
  126. dict ['key'] = 5
  127. myarray = [4,5,6]
  128. print ('foo')
  129. **NEVER**:
  130. ::
  131. x = 100
  132. y = 100
  133. velocity = 500
  134. Quotes
  135. ~~~~~~
  136. Use double quotes unless single quotes make it possible to escape fewer
  137. characters in a given string. See the examples below:
  138. ::
  139. # Normal string.
  140. print("hello world")
  141. # Use double quotes as usual to avoid escapes.
  142. print("hello 'world'")
  143. # Use single quotes as an exception to the rule to avoid escapes.
  144. print('hello "world"')
  145. # Both quote styles would require 2 escapes; prefer double quotes if it's a tie.
  146. print("'hello' \"world\"")
  147. Naming conventions
  148. ------------------
  149. These naming conventions follow the Godot Engine style. Breaking these
  150. will make your code clash with the built-in naming conventions, which is
  151. ugly.
  152. Classes and nodes
  153. ~~~~~~~~~~~~~~~~~
  154. Use PascalCase: ``extends KinematicBody``
  155. Also when loading a class into a constant or variable:
  156. ::
  157. const MyCoolNode = preload("res://my_cool_node.gd")
  158. Functions and variables
  159. ~~~~~~~~~~~~~~~~~~~~~~~
  160. Use snake\_case: ``get_node()``
  161. Prepend a single underscore (\_) to virtual methods (functions the user
  162. must override), private functions, and private variables:
  163. ``func _ready()``
  164. Signals
  165. ~~~~~~~
  166. Use past tense:
  167. ::
  168. signal door_opened
  169. signal score_changed
  170. Constants and enums
  171. ~~~~~~~~~~~~~~~~~~~
  172. Use CONSTANT\_CASE, all caps, with an underscore (\_) to separate words.
  173. Enum *names* (if any) should use PascalCase, but their *values* should be in
  174. CONSTANT\_CASE.
  175. ::
  176. const MAX_SPEED = 200
  177. enum Element {
  178. EARTH,
  179. WATER,
  180. AIR,
  181. FIRE,
  182. }
  183. Static typing
  184. -------------
  185. Since Godot 3.1, GDScript supports :ref:`optional static typing<doc_gdscript_static_typing>`.
  186. Type hints
  187. ~~~~~~~~~~
  188. Place the colon right after the variable's name, without a space, and let the GDScript compiler infer the variable's type when possible.
  189. **Good**:
  190. ::
  191. onready var health_bar: ProgressBar = get_node("UI/LifeBar")
  192. var health := 0 # The compiler will use the int type
  193. **Bad**:
  194. ::
  195. # The compiler can't infer the exact type and will use Node
  196. # instead of ProgressBar
  197. onready var health_bar := get_node("UI/LifeBar")
  198. When you let the compiler infer the type hint, write the colon and equal signs together: ``:=``.
  199. ::
  200. var health := 0 # The compiler will use the int type
  201. Add a space on either sides of the return type arrow when defining functions.
  202. ::
  203. func heal(amount: int) -> void: