Re: Nice one-liner for switching between "false" and "true"
Posted: Mon Aug 31, 2015 6:10 pm
This topic should be renamed "Thread for doing things the hard way"
Sorry, I misread the manual, or has lower precedence than and.Robin wrote: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.Inny wrote:You'll see this a lot as the ternary operator: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.Code: Select all
x = (condition) and 1 or 2
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