GDScript Match Tutorial – Complete Guide

Welcome to this tutorial on GDScript’s match keyword. This powerful feature is a game-changer in terms of writing cleaner and more efficient code and is particularly useful in game development scenarios. While the concept of match might seem complex in the beginning, understanding how to use it can make your programming journey smoother and more enjoyable.

What is GDScript’s match?

GDScript’s match is a keyword used to control the flow of a program. The match statement allows you to check a sequence of values for a match against an expression. If the expression matches a pattern, the corresponding block of code is executed. It is a more readable and efficient alternative to if-elseif-else chains.

What is it for?

The primary use of match is to simplify your code. It allows you to avoid repetitive if-elseif-else statements, which can make your code more readable and easier to maintain. With match, you can easily compare an expression against various possibilities.

Why should I learn it?

Learning how to use match in GDScript is a valuable skill for anyone interested in game development with Godot. It can help you write more efficient, organized, and clean code. Clean code becomes very important as projects increase in scale and complexity. Efficient use of GDScript’s match can make your codebase easier to navigate, understand, and modify.

As game developers, we often have to analyze and react to various scenarios, conditions, or inputs. The elegance of the ‘match’ command shines particularly in these situations, making your code more modular and your life easier.

As an education expert at Zenva, my job is to make seemingly complex topics accessible and engaging. Let’s dive into the hands-on part of our tutorial where we’ll be exploring GDScript’s match.

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

Basic Usage of match

Let’s start with the basics. Suppose we have a variable, and we want to check its value. A simple if-elif-else chain would look like this:

var my_var = 2

if my_var == 1:
    print("my_var is 1")
elif my_var == 2:
    print("my_var is 2")
else:
    print("The value of my_var is unknown")

The match keyword allows you to write the same code in a more readable and elegant way:

var my_var = 2

match my_var:
    1:
        print("my_var is 1")
    2:
        print("my_var is 2")
    _:
        print("The value of my_var is unknown")

The underscore (_) is a special pattern that matches everything. It’s common to use it as a fallback case for when no other patterns match.

Working with Enums

You often use Enums in game development to represent different states of an object. With match, handling Enums becomes a pleasant task.

enum State {Idle, Running, Jumping}

var player_state = State.Running

match player_state:
    State.Idle:
        print("Player is idle")
    State.Running:
        print("Player is running")
    State.Jumping:
        print("Player is jumping")

Pattern Matching on Arrays

With GDScript’s match, you can also pattern-match on arrays.

var my_array = [1, 2, 3]

match my_array:
    [1, 2, 3]:
        print("The array is [1, 2, 3]")
    _:
        print("The array is unknown")

Matching on Dictionary Keys

Dictionaries in GDScript are a powerful tool for storing data. Using match, it becomes easy to check for specific keys in a dictionary.

var my_dict = {"name": "John", "age": 30}

match "name" in my_dict:
    true:
        print("The key 'name' is in the dictionary")
    false:
        print("The key 'name' is not in the dictionary")

Combining Several Conditions

One of the aspects that makes match really shine is its ability to simplify complex condition checks. Consider a situation where we have multiple conditions to evaluate. Let’s say we have two variables — state and action — and we want to evaluate their combined states. With match, it becomes much simpler:

var state = "idle"
var action = "jump"

match [state, action]:
    ["idle", "jump"]:
        print("The player is idle and about to jump.")
    ["running", "jump"]:
        print("The player is running and about to jump.")
    _:
        print("Unknown combination")

Beyond Exact Matches: Using binds

Sometimes, we don’t want to check for an exact match – we just want to see if a variable falls into a certain category. This can be done using binds in match.

Think of binds as variables that are assigned during the match operation. If a pattern that consists of a bind matches the value, the bind will contain this value. This is very useful when working with types or ranges:

var my_var = 10

match my_var:
    1:
        print("The variable is 1")
    2:
        print("The variable is 2")
    var _ if my_var > 2:
        print("The variable is greater than 2")

As we can see, match is not just for exact matches. It’s a powerful command that can be adapted to various coding scenarios.

Wildcard: Matching with _

If you want to express “any value” in a pattern, you can use the underscore (_). No matter what the value is, the underscore will match it. Essentially, this wildcard character acts as a catch-all in your match condition. The underscore is typically used as the last condition after all other precise match conditions.

var character = "mage"

match character:
    "warrior", "archer", "thief":
        print("The class is physical")
    "mage", "wizard", "enchanter":
        print("The class is magical")
    _:
        print("Unknown class")

Using match with Classes

Lastly, let’s look at using match with instances of classes. With GDScript’s Match, you are not just limited to simple types like integers, strings or arrays. You can even pattern match instances of classes.

class MyClass:
    var my_var

var obj1 = MyClass.new()
obj1.my_var = "hello"

match obj1:
    MyClass:
        print("This object is an instance of MyClass")

In the above code, if obj1 is an instance of MyClass, a corresponding message will be printed to the console.

Through these examples, you can see how GDScript’s match can revolutionize your coding workflow and simplify complex conditions whether you are working with basic types of data, classes or other complex structures. Learn to wield this tool efficiently, and you’d have one less thing to worry about when tackling the more complex dynamics of game development.

Dealing with Nested Patterns

Match is powerful enough to handle nested patterns. Let’s say you have an array within an array, and you want to check for a match in this complex data structure. You can write:

var my_list = [[1,2], [3,4]]

match my_list:
    [[1,2], _]:
        print("The sublist [1,2] is found in my_list")
    _:
        print("No match found")

In the pattern [[1,2], _], the underscore acts as a wildcard. It will match any value, so this pattern will match any list that has [1,2] as its first element.

Using Multi-line Match Statements

If matching one pattern requires complex logic, you can write your match-clause across multiple lines:

var enemy = 'goblin'

match enemy:
    'goblin':
        print('A goblin appears.')
        print('You draw your sword.')
    _:
        print('An unknown creature appears.')
        print('You are on guard.')

In this case, each time ‘goblin’ is matched, two lines of code will be executed.

Handling Multiple Matches

GDScript match also supports checking for multiple patterns in the same line. For instance, if you’re checking a player’s health level and you want to handle multiple low-health values in the same way:

var health = 15

match health:
    1, 2, 3, 4, 5:
        print("Health is critically low. Find a health pack ASAP!")
    _:
        print("Player is doing fine")

As you can see, match can support multiple values for the same condition, making it much simpler to write if you require the same result for different conditions.

Comparison and Wildcard Operators

Match’s functionality becomes even more powerful when combined with comparison operators or wildcards.

var my_var = 50

match my_var:
     25 && my_var < 75:
        print("The variable is between 25 and 75")
    _:
        print("None of the conditions match")

In this case, the lower than operator (<) comparison is used to check if my_var is lower than 25, and the condition between 25 and 75 is checked using a wildcard combined with if.

Matching Function Returns

Sometimes, you might want to check the result of a function directly. You can match the function return just like any other variable.

func get_number():
    return 3

match get_number():
    1:
        print("The number is one")
    2:
        print("The number is two")
    3:
        print("The number is three")
    _:
        print("The number is unknown")

In this code, the function get_number() is called inside the match statement. The return of this function (3 in this case) is matched against the conditions.

By now, you should have a solid understanding of how to use GDScript’s match keyword for simpler and cleaner programming. Remember, practice makes perfect. Incorporate match into your projects and, over time, using match will become instinctive.

Where To Go From Here?

Now that you’ve had a taste of the power of GDScript’s match keyword, we encourage you to continue exploring and honing your game development skills. A great next step in your journey could be to check out our comprehensive and flexible learning path, the Godot Game Development Mini-Degree. This collection of courses will guide you through creating cross-platform games using the lightweight, open-source game engine, Godot 4.

The courses cover a wide range of game development topics from using 2D and 3D assets, controlling gameplay flow, creating different game mechanics like RPG, RTS, survival, and platformer, and much more. They also allow you to work on and complete your own projects, adding real Godot projects to your portfolio.

For an even wider array of resources, check out our Godot Courses. With Zenva, you can seamlessly continue your journey from a beginner to a professional. Whether you are new to coding or an experienced developer looking to expand your skillset, Zenva has over 250 supported and high-quality courses to boost your career. Learn coding, create games and earn certificates – all while fitting your learning around your lifestyle. Happy learning and game developing! You’re on your way to a fascinating and rewarding journey.

Conclusion

GDScript’s match keyword can significantly simplify your coding experience, making your programs more readable and maintainable. Dive deeper into the world of game development – the beauty lies in its complexity and the joy when your code executes perfectly. Always remember to keep learning, practicing, and exploring new features to continuously enhance your skills.

Embarking on Zenva’s Godot Game Development Mini-Degree will take you further into the intricacies of GDScript and game development. With our flexible, high-quality courses, you can learn at your own pace and develop robust skills that will set you apart as a programmer. We hope this tutorial has sparked your curiosity and interest in GDScript. Happy coding!

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.