Gdscript Typeof Tutorial – Complete Guide

Are you curious to dive deeper into GDScript, the specially designed language for Godot Engine? If your answer is yes, then you’re in the right place. This guide will take you on a comprehensive journey through GDScript’s ‘typeof’ function, a handy tool that can give you more power and control over your game development projects.

What is GDScript’s typeof?

In GDScript, ‘typeof’ is a built-in function that allows you to determine the type of a variable. Just like any major coding language, GDScript supports several variable types such as integers, strings, floats, vectors, arrays, and others. Knowing what type of data is stored in your variables is crucial when building games, as it allows you to prevent bugs and crashes that can occur if you try to perform operations suited to one data type on another.

Why Should I Learn About typeof?

Mastering the use of ‘typeof’ in GDScript can help in many ways. It gives you the power to write more robust code, debug with more ease, and even implement advanced game functionality. We believe that learning ‘typeof’ is a great confidence booster for beginners and an essential tool for advanced coders, enhancing their ability to create games with Godot more efficiently.

This is a brief intro of what we’ll be dealing with. Read on to indulge in the depths of GDScript’s ‘typeof’ function. There’s a lot to learn, so let’s dive right in.

Tutorial Part 1: Introducing typeof

Let’s start our journey with GDScript and ‘typeof’ by simply understanding what it does. Take a look at this simple script:

var my_integer = 10
var my_string = "Hello, GDScript!"
print(typeof(my_integer))  # Outputs: 1
print(typeof(my_string))   # Outputs: 4

From the example above, we can observe that the typeof function returns a number corresponding to the type of the variable. For instance, 1 represents an integer type, and 4 denotes a string.

Tutorial Part 2: Deeper Understanding of typeof

In Godot, every value is an object. Hence, typeof can return unique types for even complex structures like arrays or user-defined classes. Let’s see this in action.

class MyClass:
    var attribute

var my_object = MyClass.new()

print(typeof(my_object))  # Outputs: 17

Here, typeof returns 17, implying that the variable holds an instance of a custom class.

Tutorial Part 3: Using typeof in Decision Making

We can use the typeof function in conditioning or decision making. For instance, we can write a function that performs different operations depending on the type of the input parameter.

func operate(value):
    if typeof(value) == TYPE_INT:
        print("integer operations...")
    elif typeof(value) == TYPE_STRING:
        print("string operations...")
# You can further add more conditions to handle other data types

Continuing the Journey

Ready to take your learning to the next level? We would recommend our Godot Game Development Mini-Degree. At Zenva, we cater to learners at the beginning of their coding journey and those already experienced, providing high-quality content across programming, game creation, and AI.

Conclusion

This guide provided an in-depth understanding of the ‘typeof’ function in GDScript. You learned what it does, why you should learn it, and how to apply it in your game development projects.

Having such an understanding of ‘typeof’ means you can now write more robust and efficient game code in Godot Engine. For more such exciting learning adventures, continue with our Godot Game Development Mini-Degree.

Let’s continue coding, exploring, and learning. The coder’s journey, after all, has no end.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

How to Use ‘typeof’ with Various Data Types

Let’s start with some simple data types like integers, strings and floats. Remember, in GDscript, ‘typeof’ is going to return a number that corresponds to a constant representing a variable’s data type.

var my_integer = 12
print(typeof(my_integer))  # Outputs: 1 (integer)

var my_string = "This is GDScript."
print(typeof(my_string))  # Outputs: 4 (string)

var my_float = 3.14
print(typeof(my_float))  # Outputs: 3 (float)

Now, let’s step up a little and see how it works with complex data types like arrays, dictionaries and vector2.

var my_array = [1, 2, 3]
print(typeof(my_array))   # Outputs: 19 (array)

var my_dictionary = {"one": 1, "two": 2, "three": 3}
print(typeof(my_dictionary))  # Outputs: 18 (dictionary)

var my_vector2 = Vector2(1,2)
print(typeof(my_vector2))  # Outputs: 7 (vector2)

The typeof function even works with GDScript’s special data types like nodes and signals! This can come in handy when you’re working with various types of Nodes in a scene tree.

var my_node2D = Node2D.new()
print(typeof(my_node2D))  # Outputs: 17 (Object)

signal my_signal
print(typeof(my_signal))  # Outputs: 0 (null)

Integrating ‘typeof’ in Conditional Statements

Now that you know how ‘typeof’ function can be used with different variable types, let’s see how you can leverage this function in conditional statements to handle variables of different types.

var value = "Testing typeof"

if typeof(value) == TYPE_STRING:
 print("The variable is a string!")

elif typeof(value) == TYPE_INT:
 print("The variable is an integer!")
 
elif typeof(value) == TYPE_ARRAY:
 print("The variable is an array!")

Not just ‘if’ conditions, typeof can also be handy when you use ‘match’ statements.

var value = 5
match typeof(value):
 TYPE_INT:
 print("The variable is an integer!") 

 TYPE_FLOAT:
 print("The variable is a float!")

 TYPE_ARRAY:
 print("The variable is an array!")

So, that was all about integrating ‘typeof’ in conditional statements. As you can see, ‘typeof’ helps you to manage different data types and prevent errors in your code.

Using ‘typeof’ with Functions

The ‘typeof’ function doesn’t just work with variables – it can also be used with functions. Imagine you have a function returns something and you want to know the type of the returned value. ‘typeof’ can do that for you.

func ret_integer():
 return 5

print(typeof(ret_integer()))  # Outputs: 1 (integer)

What if your function returns a node or an instance of a custom class? ‘typeof’ has got you covered.

class MyNode:
    var attr = "This is my custom Node."

func ret_node():
 return MyNode.new()

print(typeof(ret_node()))  # Outputs: 17 (object)

Using ‘typeof’ with Custom Classes

‘typeof’ also works well with classes and can help you identify whether a variable refers to an instance of a particular class.

class MyClass1:
    var attr1

class MyClass2:
    var attr2

var my_obj1 = MyClass1.new()
var my_obj2 = MyClass2.new()

print(typeof(my_obj1))  # Outputs: 17 (object)
print(typeof(my_obj2))  # Outputs: 17 (object)

Note that ‘typeof’ returns 17 (object) for both my_obj1 and my_obj2. This happens because ‘typeof’ can identify that both variables contain class instances (or, to be more specific, instances of a class that inherits from Godot’s Object class) but it cannot differentiate between instances of different user-defined classes. For that, you would have to keep track of your class instances yourself or resort to a workaround using dictionaries or arrays.

Edge Case: Null Values and ‘typeof’

Lastly, let’s look at how ‘typeof’ behaves when a variable is null.

var nothing

print(typeof(nothing))  # Outputs: 0

Using ‘typeof’ on a null variable will give you 0. This could be useful if you are working with variables that might not have been initialized yet, and you want to check if that’s the case.

‘typeof’ and Error Handling

‘typeof’ can prove extremely useful in error handling within your game code. Suppose, you want to ensure a function gets the correct input type for carrying the calculation. You can use ‘typeof’ to ensure this consistency.

func add_numbers(num1, num2):
    if typeof(num1) != TYPE_INT or typeof(num2) != TYPE_INT:
        print("Error: Function inputs must be integers.")
        return
    else:
        return num1 + num2

var result = add_numbers("abc", 2)  # Outputs: Error: Function inputs must be integers.

The ‘add_numbers’ function here utilizes ‘typeof’ for checking if the inputs are integers. If not, it returns an error message.

‘typeof’ in Debugging

While debugging your game scripts, it is essential to understand the variable types to make the right interpretations. ‘typeof’ function lets you do that without any hassle.

var my_integer = 5
var my_array = [1, 2, 3, 4, 5]

func debug_vars():
    print("Type of my_integer: ", typeof(my_integer))
    print("Type of my_array: ", typeof(my_array))
debug_vars() 

# Output:
# Type of my_integer: 1
# Type of my_array: 19

The ‘debug_vars’ function here is used to print the types of some variables during debugging, making it easier to understand the code’s functioning.

Conditional Structures with User-defined Classes

‘typeof’ shows its true power while dealing with custom classes instances within conditional structures. Let’s have a look at an example.

class MyClass:
    var attribute

func check_class(value):
    if typeof(value) == TYPE_OBJECT and value is MyClass:
        print("The variable is an instance of MyClass.")

var my_object = MyClass.new()
check_class(my_object) # Outputs: The variable is an instance of MyClass.

The ‘check_class’ function above uses ‘typeof’ to first check that the passed value is an object, and if it is, confirms whether it’s an instance of the MyClass. If both conditions are true, it prints a message. This could be useful if you want to perform class-specific operations on an object.

‘typeof’ with Nodes in Godot

Lastly, let’s see how ‘typeof’ works with Godot’s Nodes. It comes in handy while working with various Node types within a scene.

var new_node2D = Node2D.new()
var new_sprite = Sprite.new()

print(typeof(new_node2D))  # Outputs: 17 (Object)
print(typeof(new_sprite))  # Outputs: 17 (Object)

Again, ‘typeof’ can tell you that new_node2D and new_sprite are objects. However, it doesn’t specify what kind of Nodes they are.

In conclusion, the ‘typeof’ function is a powerful tool when it comes to working with different data types in GDScript. Whether you’re coding functions, debugging your scripts, handling errors, or working with various Node types, ‘typeof’ can be a great aid in managing and controlling data types in GDScript.

Ready for Your Next Quest in Game Development?

Mastering ‘typeof’ is only the beginning of your learning adventure. There are still countless avenues in GDScript and game development waiting to be explored in the realm of the Godot Engine.

We, at Zenva, offer a comprehensive range of beginner to professional courses in programming, game development, and AI. One such offering is our Godot Game Development Mini-Degree, a thorough collection of courses designed to give you an immersive experience in creating cross-platform games using Godot 4. This mini-degree includes lessons on 2D and 3D assets, GDScript programming language, gameplay control flow, player and enemy combat, among others. Plus, our experienced instructors are certified game developers., poised to help you in your journey to become a game development professional.

In addition, if you are looking to learn more specifically about Godot Engine, you might want to check out our collection of Godot Courses. With us, you get to learn coding, create games, and earn certificates that can boost your career. Our robust learning platform is always ready to help you, from the basics to advanced topics. Let’s keep this adventure going, shall we?

Conclusion

In this guide, we took an extensive tour exploring GDScript’s ‘typeof’ function. You learned about its purpose, its powerful utility with different data types, and how it can boost the robustness and efficiency of your Godot game projects.

But remember, our journey doesn’t stop here. To further enhance your command over GDScript and to perfect your game development skills, join us at Zenva for our comprehensive Godot Game Development Mini-Degree. Let’s continue this exciting adventure of game development together, taking your coding skills to the next level, one guide at a time.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.