Howdy all, I've always missed the c-style ternary conditional operator in Lua, but I found an equivalent this summer! First, I'll explain what I'm talking about...
How many times have you run into a situation like the following?
local foo
if some_condition then
foo = "You lost, foo"
else
foo = "You won!"
end
Seems silly to have 6 lines of code for something so simple, right? In C/C++, you have an operator that helps here. The format is ( conditional_to_check ? execute_if_true : execute_if_false ). Pretty simple, huh? So to do the code we had above in C/C++, we'd do this:
foo = some_condition ? "You lost, foo!" : "You won!";
6 lines of code in one with no clarity lost! A programmer's best friend. No joy from Lua since this isn't officially supported, but you can emulate the behavior using and-or. So, the code above becomes:
foo = some_condition and "You lost, foo!" or "You won!"
It's not nearly as clear as the C/C++ operator, but it works. Why? Since 'and' takes precedence, it evaluates like this: foo = (some_condition and "You lost, foo!") or "You won!". If some_condition evaluates to true, it reads the "You lost, foo!" as well. Since the and'ed condition is true, it has no need to evaluate the second half of the or, so it returns "You lost, foo!". If some_condition is false, it doesn't bother finishing the evaluation of the and'ed condition since it can't possibly be true now. It evaluates the second half of the or and returns it.
The catches of using this method:
- The "You lost, foo!" portion of the statement must evaluate to true or it will return the code that should execute when the conditional is false.
- Since it's not part of the standard language, it might be confusing. And please, make sure you only use this method in simple conditional cases.
There you have it. Yes, I realize that any die hard Python programmers here probably already knew this. Am I going to use this? Definitely not as often as I'd use the C/C++ operator since it's just so darn confusing to look at this in Lua, but when I have a case like I outlined above it will definitely be a nice thing to have.
