Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | YAGU |
Is it somehow possible to check for a range with the match statement?
like:
match myVariable:
0 - 9:
Do this.
10 - 99:
Do that.
Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | YAGU |
Is it somehow possible to check for a range with the match statement?
like:
match myVariable:
0 - 9:
Do this.
10 - 99:
Do that.
Reply From: | exuin |
No, match checks for matches, not ranges.
True. But the idea of adding support for ranges and negations has been proposed before and is still in discussion: Add support for range comparisons and negation in `match` operations · Issue #994 · godotengine/godot-proposals · GitHub
Thomas Karcher | 2021-04-22 15:41
Reply From: | davethecoder |
I caught myself in a situation where this feature would be really really useful and save me some time and lines. I hope they implement it or something related to it. If they do and someone knows it, tell us about it, please!
Reply From: | Inces |
match
can’t do this, but if statement would be equally space-eficcient :
if range(0,9).has(x):
Also, You can introduce an array with borders of your ranges:
var borders = [0,10,100,267]
and check what index would your variable get if it was sorted into this array. Then You would be able to match
the result
Inces | 2023-01-26 16:37
With Pattern Guards, yes
var x = 123
match true:
_ when x > 100 && x < 200:
print("1")
_ when x < 100:
print("2")
_ when x > 200:
print("3")