GDScript: An introduction to dynamic languages

About

This tutorial aims to be a quick reference for how to use GDScript more efficiently. It focuses on common cases specific to the language, but also covers a lot of information on dynamically typed languages.

It’s meant to be especially useful for programmers with little or no previous experience with dynamically typed languages.

Dynamic nature

Pros & cons of dynamic typing

GDScript is a Dynamically Typed language. As such, its main advantages are that:

  • The language is easy to get started with.

  • Most code can be written and changed quickly and without hassle.

  • Less code written means less errors & mistakes to fix.

  • The code is easy to read (little clutter).

  • No compilation is required to test.

  • Runtime is tiny.

  • It has duck-typing and polymorphism by nature.

While the main disadvantages are:

  • Less performance than statically typed languages.

  • More difficult to refactor (symbols can’t be traced).

  • Some errors that would typically be detected at compile time in statically typed languages only appear while running the code (because expression parsing is more strict).

  • Less flexibility for code-completion (some variable types are only known at run-time).

This, translated to reality, means that Godot used with GDScript is a combination designed to create games quickly and efficiently. For games that are very computationally intensive and can’t benefit from the engine built-in tools (such as the Vector types, Physics Engine, Math library, etc), the possibility of using C++ is present too. This allows you to still create most of the game in GDScript and add small bits of C++ in the areas that need a performance boost.

Variables & assignment

All variables in a dynamically typed language are “variant”-like. This means that their type is not fixed, and is only modified through assignment. Example:

Static:

  1. int a; // Value uninitialized.
  2. a = 5; // This is valid.
  3. a = "Hi!"; // This is invalid.

Dynamic:

  1. var a # 'null' by default.
  2. a = 5 # Valid, 'a' becomes an integer.
  3. a = "Hi!" # Valid, 'a' changed to a string.

As function arguments:

Functions are of dynamic nature too, which means they can be called with different arguments, for example:

Static:

  1. void print_value(int value) {
  2. printf("value is %i\n", value);
  3. }
  4. [..]
  5. print_value(55); // Valid.
  6. print_value("Hello"); // Invalid.

Dynamic:

  1. func print_value(value):
  2. print(value)
  3. [..]
  4. print_value(55) # Valid.
  5. print_value("Hello") # Valid.

Pointers & referencing:

In static languages, such as C or C++ (and to some extent Java and C#), there is a distinction between a variable and a pointer/reference to a variable. The latter allows the object to be modified by other functions by passing a reference to the original one.

In C# or Java, everything not a built-in type (int, float, sometimes String) is always a pointer or a reference. References are also garbage-collected automatically, which means they are erased when no longer used. Dynamically typed languages tend to use this memory model, too. Some Examples:

  • C++:
  1. void use_class(SomeClass *instance) {
  2. instance->use();
  3. }
  4. void do_something() {
  5. SomeClass *instance = new SomeClass; // Created as pointer.
  6. use_class(instance); // Passed as pointer.
  7. delete instance; // Otherwise it will leak memory.
  8. }
  • Java:
  1. @Override
  2. public final void use_class(SomeClass instance) {
  3. instance.use();
  4. }
  5. public final void do_something() {
  6. SomeClass instance = new SomeClass(); // Created as reference.
  7. use_class(instance); // Passed as reference.
  8. // Garbage collector will get rid of it when not in
  9. // use and freeze your game randomly for a second.
  10. }
  • GDScript:
  1. func use_class(instance): # Does not care about class type
  2. instance.use() # Will work with any class that has a ".use()" method.
  3. func do_something():
  4. var instance = SomeClass.new() # Created as reference.
  5. use_class(instance) # Passed as reference.
  6. # Will be unreferenced and deleted.

In GDScript, only base types (int, float, string and the vector types) are passed by value to functions (value is copied). Everything else (instances, arrays, dictionaries, etc) is passed as reference. Classes that inherit RefCounted (the default if nothing is specified) will be freed when not used, but manual memory management is allowed too if inheriting manually from Object.

Arrays

Arrays in dynamically typed languages can contain many different mixed datatypes inside and are always dynamic (can be resized at any time). Compare for example arrays in statically typed languages:

  1. int *array = new int[4]; // Create array.
  2. array[0] = 10; // Initialize manually.
  3. array[1] = 20; // Can't mix types.
  4. array[2] = 40;
  5. array[3] = 60;
  6. // Can't resize.
  7. use_array(array); // Passed as pointer.
  8. delete[] array; // Must be freed.
  9. // or
  10. std::vector<int> array;
  11. array.resize(4);
  12. array[0] = 10; // Initialize manually.
  13. array[1] = 20; // Can't mix types.
  14. array[2] = 40;
  15. array[3] = 60;
  16. array.resize(3); // Can be resized.
  17. use_array(array); // Passed reference or value.
  18. // Freed when stack ends.

And in GDScript:

  1. var array = [10, "hello", 40, 60] # You can mix types.
  2. array.resize(3) # Can be resized.
  3. use_array(array) # Passed as reference.
  4. # Freed when no longer in use.

In dynamically typed languages, arrays can also double as other datatypes, such as lists:

  1. var array = []
  2. array.append(4)
  3. array.append(5)
  4. array.pop_front()

Or unordered sets:

  1. var a = 20
  2. if a in [10, 20, 30]:
  3. print("We have a winner!")

Dictionaries

Dictionaries are a powerful tool in dynamically typed languages. Most programmers that come from statically typed languages (such as C++ or C#) ignore their existence and make their life unnecessarily more difficult. This datatype is generally not present in such languages (or only in limited form).

Dictionaries can map any value to any other value with complete disregard for the datatype used as either key or value. Contrary to popular belief, they are efficient because they can be implemented with hash tables. They are, in fact, so efficient that some languages will go as far as implementing arrays as dictionaries.

Example of Dictionary:

  1. var d = {"name": "John", "age": 22}
  2. print("Name: ", d["name"], " Age: ", d["age"])

Dictionaries are also dynamic, keys can be added or removed at any point at little cost:

  1. d["mother"] = "Rebecca" # Addition.
  2. d["age"] = 11 # Modification.
  3. d.erase("name") # Removal.

In most cases, two-dimensional arrays can often be implemented more easily with dictionaries. Here’s a battleship game example:

  1. # Battleship Game
  2. const SHIP = 0
  3. const SHIP_HIT = 1
  4. const WATER_HIT = 2
  5. var board = {}
  6. func initialize():
  7. board[Vector2(1, 1)] = SHIP
  8. board[Vector2(1, 2)] = SHIP
  9. board[Vector2(1, 3)] = SHIP
  10. func missile(pos):
  11. if pos in board: # Something at that position.
  12. if board[pos] == SHIP: # There was a ship! hit it.
  13. board[pos] = SHIP_HIT
  14. else:
  15. print("Already hit here!") # Hey dude you already hit here.
  16. else: # Nothing, mark as water.
  17. board[pos] = WATER_HIT
  18. func game():
  19. initialize()
  20. missile(Vector2(1, 1))
  21. missile(Vector2(5, 8))
  22. missile(Vector2(2, 3))

Dictionaries can also be used as data markup or quick structures. While GDScript’s dictionaries resemble python dictionaries, it also supports Lua style syntax and indexing, which makes it useful for writing initial states and quick structs:

  1. # Same example, lua-style support.
  2. # This syntax is a lot more readable and usable.
  3. # Like any GDScript identifier, keys written in this form cannot start
  4. # with a digit.
  5. var d = {
  6. name = "John",
  7. age = 22
  8. }
  9. print("Name: ", d.name, " Age: ", d.age) # Used "." based indexing.
  10. # Indexing
  11. d["mother"] = "Rebecca"
  12. d.mother = "Caroline" # This would work too to create a new key.

For & while

Iterating using the C-style for loop in C-derived languages can be quite complex:

  1. const char** strings = new const char*[50];
  2. [..]
  3. for (int i = 0; i < 50; i++) {
  4. printf("Value: %c Index: %d\n", strings[i], i);
  5. }
  6. // Even in STL:
  7. std::list<std::string> strings;
  8. [..]
  9. for (std::string::const_iterator it = strings.begin(); it != strings.end(); it++) {
  10. std::cout << *it << std::endl;
  11. }

Because of this, GDScript makes the opinionated decision to have a for-in loop over iterables instead:

  1. for s in strings:
  2. print(s)

Container datatypes (arrays and dictionaries) are iterable. Dictionaries allow iterating the keys:

  1. for key in dict:
  2. print(key, " -> ", dict[key])

Iterating with indices is also possible:

  1. for i in range(strings.size()):
  2. print(strings[i])

The range() function can take 3 arguments:

  1. range(n) # Will count from 0 to n in steps of 1. The parameter n is exclusive.
  2. range(b, n) # Will count from b to n in steps of 1. The parameters b is inclusive. The parameter n is exclusive.
  3. range(b, n, s) # Will count from b to n, in steps of s. The parameters b is inclusive. The parameter n is exclusive.

Some examples involving C-style for loops:

  1. for (int i = 0; i < 10; i++) {}
  2. for (int i = 5; i < 10; i++) {}
  3. for (int i = 5; i < 10; i += 2) {}

Translate to:

  1. for i in range(10):
  2. pass
  3. for i in range(5, 10):
  4. pass
  5. for i in range(5, 10, 2):
  6. pass

And backwards looping done through a negative counter:

  1. for (int i = 10; i > 0; i--) {}

Becomes:

  1. for i in range(10, 0, -1):
  2. pass

While

while() loops are the same everywhere:

  1. var i = 0
  2. while i < strings.size():
  3. print(strings[i])
  4. i += 1

Custom iterators

You can create custom iterators in case the default ones don’t quite meet your needs by overriding the Variant class’s _iter_init, _iter_next, and _iter_get functions in your script. An example implementation of a forward iterator follows:

  1. class ForwardIterator:
  2. var start
  3. var current
  4. var end
  5. var increment
  6. func _init(start, stop, increment):
  7. self.start = start
  8. self.current = start
  9. self.end = stop
  10. self.increment = increment
  11. func should_continue():
  12. return (current < end)
  13. func _iter_init(arg):
  14. current = start
  15. return should_continue()
  16. func _iter_next(arg):
  17. current += increment
  18. return should_continue()
  19. func _iter_get(arg):
  20. return current

And it can be used like any other iterator:

  1. var itr = ForwardIterator.new(0, 6, 2)
  2. for i in itr:
  3. print(i) # Will print 0, 2, and 4.

Make sure to reset the state of the iterator in _iter_init, otherwise nested for-loops that use custom iterators will not work as expected.

Duck typing

One of the most difficult concepts to grasp when moving from a statically typed language to a dynamic one is duck typing. Duck typing makes overall code design much simpler and straightforward to write, but it’s not obvious how it works.

As an example, imagine a situation where a big rock is falling down a tunnel, smashing everything on its way. The code for the rock, in a statically typed language would be something like:

  1. void BigRollingRock::on_object_hit(Smashable *entity) {
  2. entity->smash();
  3. }

This way, everything that can be smashed by a rock would have to inherit Smashable. If a character, enemy, piece of furniture, small rock were all smashable, they would need to inherit from the class Smashable, possibly requiring multiple inheritance. If multiple inheritance was undesired, then they would have to inherit a common class like Entity. Yet, it would not be very elegant to add a virtual method smash() to Entity only if a few of them can be smashed.

With dynamically typed languages, this is not a problem. Duck typing makes sure you only have to define a smash() function where required and that’s it. No need to consider inheritance, base classes, etc.

  1. func _on_object_hit(object):
  2. object.smash()

And that’s it. If the object that hit the big rock has a smash() method, it will be called. No need for inheritance or polymorphism. Dynamically typed languages only care about the instance having the desired method or member, not what it inherits or the class type. The definition of Duck Typing should make this clearer:

“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck”

In this case, it translates to:

“If the object can be smashed, don’t care what it is, just smash it.”

Yes, we should call it Hulk typing instead.

It’s possible that the object being hit doesn’t have a smash() function. Some dynamically typed languages simply ignore a method call when it doesn’t exist, but GDScript is stricter, so checking if the function exists is desirable:

  1. func _on_object_hit(object):
  2. if object.has_method("smash"):
  3. object.smash()

Then, simply define that method and anything the rock touches can be smashed.


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next