This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
+2 votes

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 (26 points)

2 Answers

+1 vote

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 (188 points)
+7 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 (8,580 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 Frequently asked questions and 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 [email protected] with your username.