gdscript_advanced.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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 simple and easy to learn.
  18. - Most code can be written and changed quickly and without hassle.
  19. - Less code written means less errors & mistakes to fix.
  20. - Easier to read the code (less clutter).
  21. - No compilation is required to test.
  22. - Runtime is tiny.
  23. - 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 run-time).
  32. This, translated to reality, means that Godot+GDScript are 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:: 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:: 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:: 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:: 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_Reference` (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:: 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] # Simple, and 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} # Simple syntax
  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 simple 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 pos
  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 with a digit.
  217. var d = {
  218. name = "John",
  219. age = 22
  220. }
  221. print("Name: ", d.name, " Age: ", d.age) # Used "." based indexing
  222. # Indexing
  223. d["mother"] = "Rebecca"
  224. d.mother = "Caroline" # This would work too to create a new key
  225. For & while
  226. -----------
  227. Iterating in some statically typed languages can be quite complex:
  228. .. code:: cpp
  229. const char* strings = new const char*[50];
  230. [..]
  231. for (int i = 0; i < 50; i++)
  232. {
  233. printf("Value: %s\n", i, strings[i]);
  234. }
  235. // Even in STL:
  236. for (std::list<std::string>::const_iterator it = strings.begin(); it != strings.end(); it++) {
  237. std::cout << *it << std::endl;
  238. }
  239. This is usually greatly simplified in dynamically typed languages:
  240. ::
  241. for s in strings:
  242. print(s)
  243. Container datatypes (arrays and dictionaries) are iterable. Dictionaries
  244. allow iterating the keys:
  245. ::
  246. for key in dict:
  247. print(key, " -> ", dict[key])
  248. Iterating with indices is also possible:
  249. ::
  250. for i in range(strings.size()):
  251. print(strings[i])
  252. The range() function can take 3 arguments:
  253. ::
  254. range(n) # Will go from 0 to n-1
  255. range(b, n) # Will go from b to n-1
  256. range(b, n, s) # Will go from b to n-1, in steps of s
  257. Some statically typed programming language examples:
  258. .. code:: cpp
  259. for (int i = 0; i < 10; i++) {}
  260. for (int i = 5; i < 10; i++) {}
  261. for (int i = 5; i < 10; i += 2) {}
  262. Translate to:
  263. ::
  264. for i in range(10):
  265. pass
  266. for i in range(5, 10):
  267. pass
  268. for i in range(5, 10, 2):
  269. pass
  270. And backwards looping is done through a negative counter:
  271. ::
  272. for (int i = 10; i > 0; i--) {}
  273. Becomes:
  274. ::
  275. for i in range(10, 0, -1):
  276. pass
  277. While
  278. -----
  279. while() loops are the same everywhere:
  280. ::
  281. var i = 0
  282. while i < strings.size():
  283. print(strings[i])
  284. i += 1
  285. Custom iterators
  286. ----------------
  287. You can create custom iterators in case the default ones don't quite meet your
  288. needs by overriding the Variant class's ``_iter_init``, ``_iter_next``, and ``_iter_get``
  289. functions in your script. An example implementation of a forward iterator follows:
  290. ::
  291. class ForwardIterator:
  292. var start
  293. var current
  294. var end
  295. var increment
  296. func _init(start, stop, increment):
  297. self.start = start
  298. self.current = start
  299. self.end = stop
  300. self.increment = increment
  301. func should_continue():
  302. return (current < end)
  303. func _iter_init(arg):
  304. current = start
  305. return should_continue()
  306. func _iter_next(arg):
  307. current += increment
  308. return should_continue()
  309. func _iter_get(arg):
  310. return current
  311. And it can be used like any other iterator:
  312. ::
  313. var itr = ForwardIterator.new(0, 6, 2)
  314. for i in itr:
  315. print(i) # Will print 0, 2, and 4
  316. Make sure to reset the state of the iterator in ``_iter_init``, otherwise nested
  317. for-loops that use custom iterators will not work as expected.
  318. Duck typing
  319. -----------
  320. One of the most difficult concepts to grasp when moving from a
  321. statically typed language to a dynamic one is duck typing. Duck typing
  322. makes overall code design much simpler and straightforward to write, but
  323. it's not obvious how it works.
  324. As an example, imagine a situation where a big rock is falling down a
  325. tunnel, smashing everything on its way. The code for the rock, in a
  326. statically typed language would be something like:
  327. .. code:: cpp
  328. void BigRollingRock::on_object_hit(Smashable *entity) {
  329. entity->smash();
  330. }
  331. This way, everything that can be smashed by a rock would have to
  332. inherit Smashable. If a character, enemy, piece of furniture, small rock
  333. were all smashable, they would need to inherit from the class Smashable,
  334. possibly requiring multiple inheritance. If multiple inheritance was
  335. undesired, then they would have to inherit a common class like Entity.
  336. Yet, it would not be very elegant to add a virtual method ``smash()`` to
  337. Entity only if a few of them can be smashed.
  338. With dynamically typed languages, this is not a problem. Duck typing
  339. makes sure you only have to define a ``smash()`` function where required
  340. and that's it. No need to consider inheritance, base classes, etc.
  341. ::
  342. func _on_object_hit(object):
  343. object.smash()
  344. And that's it. If the object that hit the big rock has a smash() method,
  345. it will be called. No need for inheritance or polymorphism. Dynamically
  346. typed languages only care about the instance having the desired method
  347. or member, not what it inherits or the class type. The definition of
  348. Duck Typing should make this clearer:
  349. *"When I see a bird that walks like a duck and swims like a duck and
  350. quacks like a duck, I call that bird a duck"*
  351. In this case, it translates to:
  352. *"If the object can be smashed, don't care what it is, just smash it."*
  353. Yes, we should call it Hulk typing instead.
  354. It's possible that the object being hit doesn't have a smash() function.
  355. Some dynamically typed languages simply ignore a method call when it
  356. doesn't exist (like Objective C), but GDScript is stricter, so
  357. checking if the function exists is desirable:
  358. ::
  359. func _on_object_hit(object):
  360. if object.has_method("smash"):
  361. object.smash()
  362. Then, simply define that method and anything the rock touches can be
  363. smashed.