Currently I am using an if statement but I will have many more if statements by the time I'm through with the project. I was hoping to swap over to a match statement that should be able to process faster than an if statement. These are custom classes. Here is my current code:

			var detected = interact_ray.get_collider()

			if detected is Sign:
				handle_chat_box(detected)
			elif detected is Rocks:
				handle_ore_interact(detected)
			elif detected is Chopable:
				handle_tree_interact(detected)
				pass
			else:
				interact_ray.get_collider().player_interact()

Is there a way to put this in a match statement?
This doesn't work because I'm passing in the object and not the objects class, where above I'm using the "is" statement to check the custom class of the object.

			var detected = interact_ray.get_collider()
			
			match detected:
				Sign:
					print("Sign")
				Rocks:
					print("Rocks")
				Chopable:
					print("Trees")
  • Toxe replied to this.

    What’s your reasoning behind a match being faster?

    Would like to know what makes the handle_* functions different enough to use conditional logic too. Looks like a code smell?

    If you put the different kinds of objects (Sign, Rocks, Trees) in different groups, then you could match on the group name.

    KlownHero There are a couple of ways to deal with this.

    Option 1: Use the class names in your match.

    match detected.get_class():
        "Sign": handle_sign(detected)
        "Rock": handle_rock(detected)

    Depending on the complexity you could simulate an interface.

    Option 2: Give those objects a base class like for example Interactable that has a function interact() that the sub classes can overwrite.

    var detected = interact_ray.get_collider()
    
    if detected is Interactable:
        detected.interact()

    Option 3: Add a common function like for example handle_interaction() to those classes.

    var detected = interact_ray.get_collider()
    
    if "handle_interaction" in detected:
        detected.handle_interaction()

    But of course both options mean that you need to add whatever logic is necessary to handle with an interaction to all those classes. If you want to keep all that in one place then this won't work.

    Option 4: Make a dictionary that holds Callables and use the class names as keys. Then do something like:

    if detected.get_class() in dict:
        dict[detected.get_class()].call(detected)

    That way you can keep all the logic together in your current script.

    Match won't run any faster than ifs. This will probably never be a performance bottleneck anyway so keep it simple and just use ifs.