Match statement not evaluating properly

Godot Version

4.4.1

Question

So I have a class Expander0 which is a scene of UI nodes used to open a dropdown panel when pressed. One of the variables in the class is Direction, which is exported; I have a test instance of Expander0 in my main scene with its Direction set to “0Up” in the inspector. Another variable in the class is DirectionOpposite, which is intended to be a String of the opposite direction, corresponding to “1Down” in my directional system if Direction is “0Up”; DirectionOpposite is determined at ready depending on the value of Direction, being assigned to the return of function Get_DirectionOpposite via the function’s match statement.

The class also has static var CurInst, which keeps track of the most recent or “active” instance of the class; since I only have one instance of Expander0 in the main scene, it is equivalent to CurInst in this situation.

However, the match statement is returning false on all of its conditions even though the Direction of this instance of Expander0 is set to “0Up”, and it’s clear that this value of CurInst.Direction is known by the code when Get_DirectionOpposite is called (as the test print(CurInst.Direction); returns “0Up” as it should); thus I would expect the match statement to return “1Down” here, but it is returning Nil and thus an error is thrown since the line DirectionOpposite = Get_DirectionOpposite(); is assigning DirectionOpposite to this Nil value instead of “1Down” like it should be.


You can add a _ option to the match for a default case:

match(foo):
    "banana": print("got a banana!")
    _:        print("Huh, got:" + str(foo))

That won’t solve your problem, obviously, but it might help debug.

What happens if you print the value of CurInst inside Get_DirectionOpposite()? Is CurInst coming up empty, or is CurInst.Direction visible but uninitialized?

1 Like

Actually I just found the problem - since I set Direction of the test instance to “0Up” in the inspector, the value of CurInst.Direction contained those quotes within the String so it was actually set to ““0Up”” instead of “0Up”. I had a feeling it was a minor mistake on my part. Thanks for the reply though mate; I didn’t know about the ability to denote a match’s default condition with _: so I learned something new anyway!

For this kind of thing, enum can be a lifesaver. It gives you a well defined, fixed set of values that your variable can be, which means you can do exhaustive tests. Something like:

enum DIRECTION { none,up, down, left, right }

func Get_DirectionOpposite() -> DIRECTION:
    match(CurInst.Direction):
        DIRECTION.none:  return DIRECTION.none
        DIRECTION.up:    return DIRECTION.down
        DIRECTION.down:  return DIRECTION.up
        DIRECTION.left:  return DIRECTION.right
        DIRECTION.right: return DIRECTION.left
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.