Nice one-liner for switching between "false" and "true"
Re: Nice one-liner for switching between "false" and "true"
This topic should be renamed "Thread for doing things the hard way"
My game called Hat Cat and the Obvious Crimes Against the Fundamental Laws of Physics is out now!
Re: Nice one-liner for switching between "false" and "true"
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
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
Who is online
Users browsing this forum: No registered users and 10 guests