What is a match statement in GDSCRIPT and how we can use it?
In this article, We will discuss is a match statement in GDSCRIPT and how we can use it. so let’s start.
A match statement, just like a switch case statement in many other programming languages but offers some additional features, is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution in search and map.
Basically, you use a variable to ‘match’ a pattern and execute the code inside the match statement
Basic syntax :
Types of match patterns
1.Constant Pattern
2.Variable Pattern
3.Wildcard Pattern
4.Binding Pattern
5.Array Pattern
6.Dictionary Pattern
7.Multiple Pattern
1.Constant Pattern
A constant pattern is when you use a primitive/literal data type.
primitive/literal data types are integers, floats, booleans, strings, etc.
Example :
2. Variable Pattern :
With Gdscript we can use variables to match a pattern
3. Wildcard Pattern :
wildcard pattern matches everything. It’s written as a single underscore_
.
It can also be thought of as a “default” block statement, meaning it will always run when all other match patterns fail
4.Binding pattern.
A binding pattern catches everything just like the wildcard pattern. The difference is the binding pattern assigns the value acquired into a variable that can be used inside the binding pattern match block
It’s especially useful in array and dictionary patterns