function _if(bool, func1, func2)
if bool then return func1() else return func2() end
end
The above piece of code returns func1() if bool is true and func2() else.
The following code will return func2() if bool is not true or if bool is true and func1() is not true. It will only return func1() if both bool and func1() are true.
function _if(bool, func1, func2)
return bool and func1() or func2()
end
The last piece of code will return func1() if bool is true and func2() else.
function _if(bool, func1, func2)
return (bool and func1 or func2)()
end
So first of all, Lua does not have any ternary operator. The clever use of and's higher precedence over or is just equivalent to ternary operators like C's ?:
Second the expression a = b and c or d will only work properly if c is true. This may not always be the case if you're using a function call as c.
It's a convenient way to do assignments but in many cases it increases readability and reduces mistakes to just stick to an if else statement.
Once you have to add more conditions that and or trick becomes a total mess.
So let's have another look on what is going on in the second snippet.
function _if(bool, func1, func2)
return bool and func1() or func2()
end
First bool and func1() will be evaluated.
If bool isn't true, Lua does not have to call func1() because the expression can never be true.
So Lua can go and evaluate func2() right away.
Your function will return func2()!
On the opposite, if bool is true, Lua will call func1() to see if it also true.
if func1() returns true, Lua will not call func2(). Because of the following or the expression will always be true if bool and func1() is true.
if func1() returns false/nil the or has to be evaluated. So Lua will call func2() as well and then return it's return value.
It is important to know operator precedence and in which cases Lua will abort evaluating expressions!
Lua's or and and operators use short-cut evaluation. The second operand is only evaluated if necessary