+1 vote

As a beginner, I'm having trouble understanding when it'd be better to use a bunch of "ifs", and when "match" is the way to go.

I have a simple state machine in the puzzle game I'm making; just 4 possible states. Input is handled differently depending on the state the game's in. So I'm doing something like this:

func _unhandled_input(event: InputEvent) -> void:
 if state == 1:
 elif state == 2:

Would I benefit from replacing this with "match", like so:

func _unhandled_input(event: InputEvent) -> void:
 match state:

If not, would "match" be a better choice in significantly more complex cases?

in Engine by (25 points)

2 Answers

0 votes

It's only my opinion, and I don't know precisely how the two are different, but I think if statements are better when handling conditions, and match when handling the possible values of a variable. So in your case I would say that match is better suited.
But again, I'm not familiar of the deep functionning of both.

by (176 points)
+2 votes

Match statements are Gdscript's equivalent of switch statements. They're faster than if statements, but if your if statement is small, there's not really any point in switching to a match statement.

by (7,190 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.