gdscript_advanced.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. .. _doc_gdscript_more_efficiently:
  2. GDScript: An introduction to dynamic languages
  3. ==============================================
  4. About
  5. -----
  6. This tutorial aims to be a quick reference for how to use GDScript more
  7. efficiently. It focuses on common cases specific to the language, but
  8. also covers a lot of information on dynamically typed languages.
  9. It's meant to be especially useful for programmers with little or no previous
  10. experience with dynamically typed languages.
  11. Dynamic nature
  12. --------------
  13. Pros & cons of dynamic typing
  14. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  15. GDScript is a Dynamically Typed language. As such, its main advantages
  16. are that:
  17. - The language is easy to get started with.
  18. - Most code can be written and changed quickly and without hassle.
  19. - Less code written means less errors & mistakes to fix.
  20. - The code is easy to read (little clutter).
  21. - No compilation is required to test.
  22. - Runtime is tiny.
  23. - It has duck-typing and polymorphism by nature.
  24. While the main disadvantages are:
  25. - Less performance than statically typed languages.
  26. - More difficult to refactor (symbols can't be traced).
  27. - Some errors that would typically be detected at compile time in
  28. statically typed languages only appear while running the code
  29. (because expression parsing is more strict).
  30. - Less flexibility for code-completion (some variable types are only
  31. known at runtime).
  32. This, translated to reality, means that Godot used with GDScript is a combination
  33. designed to create games quickly and efficiently. For games that are very
  34. computationally intensive and can't benefit from the engine built-in
  35. tools (such as the Vector types, Physics Engine, Math library, etc), the
  36. possibility of using C++ is present too. This allows you to still create most of the
  37. game in GDScript and add small bits of C++ in the areas that need
  38. a performance boost.
  39. Variables & assignment
  40. ~~~~~~~~~~~~~~~~~~~~~~
  41. All variables in a dynamically typed language are "variant"-like. This
  42. means that their type is not fixed, and is only modified through
  43. assignment. Example:
  44. Static:
  45. .. code-block:: cpp
  46. int a; // Value uninitialized.
  47. a = 5; // This is valid.
  48. a = "Hi!"; // This is invalid.
  49. Dynamic:
  50. ::
  51. var a # 'null' by default.
  52. a = 5 # Valid, 'a' becomes an integer.
  53. a = "Hi!" # Valid, 'a' changed to a string.
  54. As function arguments:
  55. ~~~~~~~~~~~~~~~~~~~~~~
  56. Functions are of dynamic nature too, which means they can be called with
  57. different arguments, for example:
  58. Static:
  59. .. code-block:: cpp
  60. void print_value(int value) {
  61. printf("value is %i\n", value);
  62. }
  63. [..]
  64. print_value(55); // Valid.
  65. print_value("Hello"); // Invalid.
  66. Dynamic:
  67. ::
  68. func print_value(value):
  69. print(value)
  70. [..]
  71. print_value(55) # Valid.
  72. print_value("Hello") # Valid.
  73. Pointers & referencing:
  74. ~~~~~~~~~~~~~~~~~~~~~~~
  75. In static languages, such as C or C++ (and to some extent Java and C#),
  76. there is a distinction between a variable and a pointer/reference to a
  77. variable. The latter allows the object to be modified by other functions
  78. by passing a reference to the original one.
  79. In C# or Java, everything not a built-in type (int, float, sometimes
  80. String) is always a pointer or a reference. References are also
  81. garbage-collected automatically, which means they are erased when no
  82. longer used. Dynamically typed languages tend to use this memory model,
  83. too. Some Examples:
  84. - C++:
  85. .. code-block:: cpp
  86. void use_class(SomeClass *instance) {
  87. instance->use();
  88. }
  89. void do_something() {
  90. SomeClass *instance = new SomeClass; // Created as pointer.
  91. use_class(instance); // Passed as pointer.
  92. delete instance; // Otherwise it will leak memory.
  93. }
  94. - Java:
  95. .. code-block:: java
  96. @Override
  97. public final void use_class(SomeClass instance) {
  98. instance.use();
  99. }
  100. public final void do_something() {
  101. SomeClass instance = new SomeClass(); // Created as reference.
  102. use_class(instance); // Passed as reference.
  103. // Garbage collector will get rid of it when not in
  104. // use and freeze your game randomly for a second.
  105. }
  106. - GDScript:
  107. ::
  108. func use_class(instance): # Does not care about class type
  109. instance.use() # Will work with any class that has a ".use()" method.
  110. func do_something():
  111. var instance = SomeClass.new() # Created as reference.
  112. use_class(instance) # Passed as reference.
  113. # Will be unreferenced and deleted.
  114. In GDScript, only base types (int, float, string and the vector types)
  115. are passed by value to functions (value is copied). Everything else
  116. (instances, arrays, dictionaries, etc) is passed as reference. Classes
  117. that inherit :ref:`class_RefCounted` (the default if nothing is specified)
  118. will be freed when not used, but manual memory management is allowed too
  119. if inheriting manually from :ref:`class_Object`.
  120. Arrays
  121. ------
  122. Arrays in dynamically typed languages can contain many different mixed
  123. datatypes inside and are always dynamic (can be resized at any time).
  124. Compare for example arrays in statically typed languages:
  125. .. code-block:: cpp
  126. int *array = new int[4]; // Create array.
  127. array[0] = 10; // Initialize manually.
  128. array[1] = 20; // Can't mix types.
  129. array[2] = 40;
  130. array[3] = 60;
  131. // Can't resize.
  132. use_array(array); // Passed as pointer.
  133. delete[] array; // Must be freed.
  134. // or
  135. std::vector<int> array;
  136. array.resize(4);
  137. array[0] = 10; // Initialize manually.
  138. array[1] = 20; // Can't mix types.
  139. array[2] = 40;
  140. array[3] = 60;
  141. array.resize(3); // Can be resized.
  142. use_array(array); // Passed reference or value.
  143. // Freed when stack ends.
  144. And in GDScript:
  145. ::
  146. var array = [10, "hello", 40, 60] # You can mix types.
  147. array.resize(3) # Can be resized.
  148. use_array(array) # Passed as reference.
  149. # Freed when no longer in use.
  150. In dynamically typed languages, arrays can also double as other
  151. datatypes, such as lists:
  152. ::
  153. var array = []
  154. array.append(4)
  155. array.append(5)
  156. array.pop_front()
  157. Or unordered sets:
  158. ::
  159. var a = 20
  160. if a in [10, 20, 30]:
  161. print("We have a winner!")
  162. Dictionaries
  163. ------------
  164. Dictionaries are a powerful tool in dynamically typed languages.
  165. Most programmers that come from statically typed languages (such as C++
  166. or C#) ignore their existence and make their life unnecessarily more
  167. difficult. This datatype is generally not present in such languages (or
  168. only in limited form).
  169. Dictionaries can map any value to any other value with complete
  170. disregard for the datatype used as either key or value. Contrary to
  171. popular belief, they are efficient because they can be implemented
  172. with hash tables. They are, in fact, so efficient that some languages
  173. will go as far as implementing arrays as dictionaries.
  174. Example of Dictionary:
  175. ::
  176. var d = {"name": "John", "age": 22}
  177. print("Name: ", d["name"], " Age: ", d["age"])
  178. Dictionaries are also dynamic, keys can be added or removed at any point
  179. at little cost:
  180. ::
  181. d["mother"] = "Rebecca" # Addition.
  182. d["age"] = 11 # Modification.
  183. d.erase("name") # Removal.
  184. In most cases, two-dimensional arrays can often be implemented more
  185. easily with dictionaries. Here's a battleship game example:
  186. ::
  187. # Battleship Game
  188. const SHIP = 0
  189. const SHIP_HIT = 1
  190. const WATER_HIT = 2
  191. var board = {}
  192. func initialize():
  193. board[Vector2(1, 1)] = SHIP
  194. board[Vector2(1, 2)] = SHIP
  195. board[Vector2(1, 3)] = SHIP
  196. func missile(pos):
  197. if pos in board: # Something at that position.
  198. if board[pos] == SHIP: # There was a ship! hit it.
  199. board[pos] = SHIP_HIT
  200. else:
  201. print("Already hit here!") # Hey dude you already hit here.
  202. else: # Nothing, mark as water.
  203. board[pos] = WATER_HIT
  204. func game():
  205. initialize()
  206. missile(Vector2(1, 1))
  207. missile(Vector2(5, 8))
  208. missile(Vector2(2, 3))
  209. Dictionaries can also be used as data markup or quick structures. While
  210. GDScript's dictionaries resemble python dictionaries, it also supports Lua
  211. style syntax and indexing, which makes it useful for writing initial
  212. states and quick structs:
  213. ::
  214. # Same example, lua-style support.
  215. # This syntax is a lot more readable and usable.
  216. # Like any GDScript identifier, keys written in this form cannot start
  217. # with a digit.
  218. var d = {
  219. name = "John",
  220. age = 22
  221. }
  222. print("Name: ", d.name, " Age: ", d.age) # Used "." based indexing.
  223. # Indexing
  224. d["mother"] = "Rebecca"
  225. d.mother = "Caroline" # This would work too to create a new key.
  226. For & while
  227. -----------
  228. Iterating using the C-style for loop in C-derived languages can be quite complex:
  229. .. code-block:: cpp
  230. const char** strings = new const char*[50];
  231. [..]
  232. for (int i = 0; i < 50; i++) {
  233. printf("Value: %c Index: %d\n", strings[i], i);
  234. }
  235. // Even in STL:
  236. std::list<std::string> strings;
  237. [..]
  238. for (std::string::const_iterator it = strings.begin(); it != strings.end(); it++) {
  239. std::cout << *it << std::endl;
  240. }
  241. Because of this, GDScript makes the opinionated decision to have a for-in loop over iterables instead:
  242. ::
  243. for s in strings:
  244. print(s)
  245. Container datatypes (arrays and dictionaries) are iterable. Dictionaries
  246. allow iterating the keys:
  247. ::
  248. for key in dict:
  249. print(key, " -> ", dict[key])
  250. Iterating with indices is also possible:
  251. ::
  252. for i in range(strings.size()):
  253. print(strings[i])
  254. The range() function can take 3 arguments:
  255. ::
  256. range(n) # Will count from 0 to n in steps of 1. The parameter n is exclusive.
  257. range(b, n) # Will count from b to n in steps of 1. The parameters b is inclusive. The parameter n is exclusive.
  258. range(b, n, s) # Will count from b to n, in steps of s. The parameters b is inclusive. The parameter n is exclusive.
  259. Some examples involving C-style for loops:
  260. .. code-block:: cpp
  261. for (int i = 0; i < 10; i++) {}
  262. for (int i = 5; i < 10; i++) {}
  263. for (int i = 5; i < 10; i += 2) {}
  264. Translate to:
  265. ::
  266. for i in range(10):
  267. pass
  268. for i in range(5, 10):
  269. pass
  270. for i in range(5, 10, 2):
  271. pass
  272. And backwards looping done through a negative counter:
  273. ::
  274. for (int i = 10; i > 0; i--) {}
  275. Becomes:
  276. ::
  277. for i in range(10, 0, -1):
  278. pass
  279. While
  280. -----
  281. while() loops are the same everywhere:
  282. ::
  283. var i = 0
  284. while i < strings.size():
  285. print(strings[i])
  286. i += 1
  287. Custom iterators
  288. ----------------
  289. You can create custom iterators in case the default ones don't quite meet your
  290. needs by overriding the Variant class's ``_iter_init``, ``_iter_next``, and ``_iter_get``
  291. functions in your script. An example implementation of a forward iterator follows:
  292. ::
  293. class ForwardIterator:
  294. var start
  295. var current
  296. var end
  297. var increment
  298. func _init(start, stop, increment):
  299. self.start = start
  300. self.current = start
  301. self.end = stop
  302. self.increment = increment
  303. func should_continue():
  304. return (current < end)
  305. func _iter_init(arg):
  306. current = start
  307. return should_continue()
  308. func _iter_next(arg):
  309. current += increment
  310. return should_continue()
  311. func _iter_get(arg):
  312. return current
  313. And it can be used like any other iterator:
  314. ::
  315. var itr = ForwardIterator.new(0, 6, 2)
  316. for i in itr:
  317. print(i) # Will print 0, 2, and 4.
  318. Make sure to reset the state of the iterator in ``_iter_init``, otherwise nested
  319. for-loops that use custom iterators will not work as expected.
  320. Duck typing
  321. -----------
  322. One of the most difficult concepts to grasp when moving from a
  323. statically typed language to a dynamic one is duck typing. Duck typing
  324. makes overall code design much simpler and straightforward to write, but
  325. it's not obvious how it works.
  326. As an example, imagine a situation where a big rock is falling down a
  327. tunnel, smashing everything on its way. The code for the rock, in a
  328. statically typed language would be something like:
  329. .. code-block:: cpp
  330. void BigRollingRock::on_object_hit(Smashable *entity) {
  331. entity->smash();
  332. }
  333. This way, everything that can be smashed by a rock would have to
  334. inherit Smashable. If a character, enemy, piece of furniture, small rock
  335. were all smashable, they would need to inherit from the class Smashable,
  336. possibly requiring multiple inheritance. If multiple inheritance was
  337. undesired, then they would have to inherit a common class like Entity.
  338. Yet, it would not be very elegant to add a virtual method ``smash()`` to
  339. Entity only if a few of them can be smashed.
  340. With dynamically typed languages, this is not a problem. Duck typing
  341. makes sure you only have to define a ``smash()`` function where required
  342. and that's it. No need to consider inheritance, base classes, etc.
  343. ::
  344. func _on_object_hit(object):
  345. object.smash()
  346. And that's it. If the object that hit the big rock has a smash() method,
  347. it will be called. No need for inheritance or polymorphism. Dynamically
  348. typed languages only care about the instance having the desired method
  349. or member, not what it inherits or the class type. The definition of
  350. Duck Typing should make this clearer:
  351. *"When I see a bird that walks like a duck and swims like a duck and
  352. quacks like a duck, I call that bird a duck"*
  353. In this case, it translates to:
  354. *"If the object can be smashed, don't care what it is, just smash it."*
  355. Yes, we should call it Hulk typing instead.
  356. It's possible that the object being hit doesn't have a smash() function.
  357. Some dynamically typed languages simply ignore a method call when it
  358. doesn't exist, but GDScript is stricter, so checking if the function
  359. exists is desirable:
  360. ::
  361. func _on_object_hit(object):
  362. if object.has_method("smash"):
  363. object.smash()
  364. Then, simply define that method and anything the rock touches can be
  365. smashed.