"Match" and "if": when to use each?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By maforn

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:
  print("1")
 elif state == 2:
  print("2")
 #etc.

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

func _unhandled_input(event: InputEvent) -> void:
 match state:
  1:
   print("1")
  2:
   print("2")
 #etc.

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

:bust_in_silhouette: Reply From: IvanVoirol

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.

:bust_in_silhouette: Reply From: exuin

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.