Page 2 of 2

Re: Nice one-liner for switching between "false" and "true"

Posted: Mon Aug 31, 2015 6:10 pm
by T-Bone
This topic should be renamed "Thread for doing things the hard way" :P

Re: Nice one-liner for switching between "false" and "true"

Posted: Tue Sep 01, 2015 1:12 am
by Inny
Robin wrote:
Inny wrote:You'll see this a lot as the ternary operator:

Code: Select all

x = (condition) and 1 or 2
But it doesn't work with nil in the 1st position, because or has higher precedence than, and (nil or 2) is always 2 as defined in 2.5.3.
I think what you mean is if you have C and A or B, it doesn't work if A is falsy (which, in Lua, means false or nil), which is true, but the reason isn't correct. C and A or B is equivalent to (C and A) or B, not C and (A or B), because the latter never works, because it's either equal to C and A (if A is truthy) or C and B (if A is falsy), and you want the choice between A and B to depend on C, not on A.
Sorry, I misread the manual, or has lower precedence than and.

For anyone else wondering what we're on about, here's what I'm talking about:

Code: Select all

> = true and 1 or 2
1
> = false and 1 or 2
2
> = true and nil or 2
2
> = false and nil or 2
2
> = true and 1 or nil
1
> = false and 1 or nil
nil
> = true and false or 2
2
The false and nil or 2 makes logical sense because (falsey and falsey) or true returns true, but the way lua works with returning the literal value from the logical statement, rather than the logical value, means that the (condition) and value or value style only works when the 1st value is truthy (as demonstrated by the last line in my code block above).