Switch in GDScript
Our first program will demonstrate the usage of switch
statements, which express conditionals across many branches.
Basic switch
Statement
Here’s a basic switch
example in GDScript:
extends Node
func _ready():
var i = 2
print("Write ", i, " as ")
match i:
1:
print("one")
2:
print("two")
3:
print("three")
Multiple Expressions in case
and default
case
You can use commas to separate multiple expressions in the same case
statement. We use the optional default
case in this example as well.
extends Node
func _ready():
match OS.get_date().weekday:
6, 7:
print("It's the weekend")
_:
print("It's a weekday")
switch
Without an Expression
match
without an expression is an alternate way to express if/else logic. Here we also show how the case
expressions can be non-constants.
extends Node
func _ready():
var t = OS.get_time()
match true:
t.hour < 12:
print("It's before noon")
_:
print("It's after noon")
Type switch
A type match
compares types instead of values. You can use this to discover the type of a value. In this example, the variable t
will have the type corresponding to its clause.
extends Node
func _ready():
func what_am_i(i):
match i:
true:
print("I'm a bool")
1:
print("I'm an int")
_:
print("Don't know type %s" % typeof(i))
what_am_i(true)
what_am_i(1)
what_am_i("hey")
Running the Code
To run the program, put the code in a GDScript file, attach it to a Node, and run the scene.
$ godot -s my_script.gd
Outputs:
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string
In this example, we’ve learned how to use switch
(or match
in GDScript) to handle multiple conditional branches efficiently.