Lua-like variable assignment depending on condition

Godot Version



This is probably a silly question, but in Lua there is a clever feature: if I want to give a variable x the value val1 if some condition is true, and otherwise the value val2, then I can bypass an annoying if-then clause by just being clever with booleans, viz.:

x = condition and val1 or val2

Then x will have the value val1 if and only if the boolean condition is true; otherwise x will have the value val2.

Is something similar possible in GDScript? In other words, I want to write a single line such that the value of x is determined by one of two possible choices.

You’re looking for the Ternary Operator

var x = val1 if condition else val2

1 Like

Ah, fantastic, I knew there was a simple answer! Thank you!

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