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

General discussion about LÖVE, Lua, game development, puns, and unicorns.
User avatar
T-Bone
Inner party member
Posts: 1492
Joined: Thu Jun 09, 2011 9:03 am

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

Post by T-Bone »

This topic should be renamed "Thread for doing things the hard way" :P
User avatar
Inny
Party member
Posts: 652
Joined: Fri Jan 30, 2009 3:41 am
Location: New York

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

Post 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).
Post Reply

Who is online

Users browsing this forum: No registered users and 7 guests