Execute Conditional Using Matching String

Godot Version

4.3

Question

I am writing something that involves parsing a string, and depending on a section of it doing math depending on the input, currently the code looks like this;

var results : PackedInt64Array = [] # this would have two items
match operator:
		"==":
			return results[int(items[0] == items[1])]
		"!=":
			return results[int(items[0] != items[1])]
		">>":
			return results[int(items[0] >> items[1])]
		">=":
			return results[int(items[0] >= items[1])]
		"<<":
			return results[int(items[0] << items[1])]
		"<=":
			return results[int(items[0] <= items[1])]
	return -1 # if match was unsuccessful 

I was wondering if there was a way to change it so, for example;

var results : PackedInt64Array = [] # this would have two items
if operator in ["==", "!=", ">>", ">=", "<<", "<="]:
	return results[int(items[0] (operator) items[1])]
	# so if operator was '==' it would execute;
	# 'return results[int(condition[0] == condition[1])]
return -1 # if the operator isnt valid

Is something like this possible, or do I have to keep doing it the first way?

Thanks.

I think what you want is the Expression class

1 Like

Yes! Thank you this is exactly what I needed, and also helps simplify another part of code I had written prior, I can’t believe I had never heard or seen anything about this before now!

Why don’t more tutorials/tips-n-tricks videos mention this class? It’s so helpful.

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