Tom
Tom

Reputation: 6971

Lua ternary operator - multiple variables

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?

Upvotes: 5

Views: 1758

Answers (1)

filmor
filmor

Reputation: 32212

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.

Upvotes: 7

Related Questions