gdscript_styleguide.rst 15 KB

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