Alternative to the ternary operator in GDScript

Coming from a C/C++ background, the ternary operator in GDScript doesn’t feel as short and concise as the ? : version in C and similar languages.

In C-style languages, variable assignments using ternary operators look like this:
int v = boolean_condition ? a : b

Compared this to the GDScript ternary operator:
var v = a if boolean_condition else b

The biggest problem to me is that the 2 different values that can be assigned to the variable are too far apart, and that the condition is in the middle. But I’ve now started to use another approach that might be useful to others as well.

var v = [b, a][int(boolean_condition)]

Here the 2 potential assignments appear side by side, just as in the C-style version. Just be aware that they must appear in reverse order (if the boolean logic should be maintained), since false becomes 0, and true becomes 1. Another pitfall to be aware of with the approach is that the condition must be a true boolean condition.

7 Likes

The array-based approach creates the array and evaluates all its values every time the condition has to be evaluated, so keep this in mind as it can negatively affect performance. The same goes with the Dictionary-based variant (although it’s even more expensive in this case).

3 Likes

Yes, it’s not a good approach for code that needs a lot of looping - only suitable for occasional assignments.

FWIW, I did some tests in a loop (where the condition was the loop int counter % 2, so the assignments where evenly split), and the array version was about 5 times slower than GDScript’s ternary operator.
And in my test, the GDScript ternary operator was also about 20% faster than the traditional multi-line if: else: statement in GDScript.

And all versions gained performance by using static typing in the assignment, which relatively speeds up the fastest approach even more (barely matter in the array-based approach, since the bottleneck is elsewhere). GDScript’s ternary operator assignment gained around 15-20% speed just by assigning to a static type, such as:
var v : int = 3 if (i % 2) else 8

5 Likes