5

Say I want to assign two values to two variables if a certain condition is true, and two different values if said condition is false. I would assume it would be done like this:

a, b = 4 > 5 and 1, 2 or 3, 4

However this assigns a to be false, and b to be 2. If we have:

a, b = 4 < 5 and 1, 2 or 3, 4

This correctly assigns a to be 1 and b to be 2.

What am I missing here, how can I get the "ternary operator" to work as I expect?

Alexander Gladysh
  • 39,865
  • 32
  • 103
  • 160
Tom
  • 6,601
  • 12
  • 40
  • 48
  • 6
    Ternary operator doesn't work with tuples of values, only with single values. But you can work with arrays: `a, b = unpack(4 > 5 and {1,2} or {3,4})` – Egor Skriptunoff Aug 18 '14 at 11:50
  • The usual "ternary operator" (so called because it takes three operands) is of the form `expr1 ? expr2 : expr3`. It's also called the "conditional operator". Lua has no such operator. – Keith Thompson Aug 18 '14 at 16:28
  • 1
    @KeithThompson `x and y or z` is equivalent as long as `y` is not false or nil (which isn't usually the case). – Colonel Thirty Two Aug 18 '14 at 16:57

1 Answers1

7

You are missing that Lua's and and or are short-cutting and commas are lower in the hierarchy. Basically what happens here is that first 4 > 5 and 1 is evaluated to false and 2 or 3 is evaluated to 2, the 4 is ignored. In the second case 4 < 5 is true, thus 4 < 5 and 1 is 1, the rest stays as it is.

As Egor Skriptunoff suggested you can do

a, b = unpack(4 > 5 and {1,2} or {3,4})

instead.

filmor
  • 30,840
  • 6
  • 50
  • 48
  • This merely explains why it is behaving like that. It doesn't provide a solution. – Bartek Banachewicz Aug 18 '14 at 11:51
  • Yes, that is right. My Lua got a bit rusty over the years so I had to poke around a bit to find the same solution as given in the comments. – filmor Aug 18 '14 at 11:56
  • 4
    Just as a side-note: Using a normal `if ... then else end` construct here would be far more efficient, if that's of any concern. – Deduplicator Aug 18 '14 at 13:54