Lua Trimage Operator – Multiple variables

Suppose I want to assign two values ​​to two variables when a certain condition is true, and two different values ​​if the condition is false. I will assume it will be like this Do:

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

However, this is designated as false, and b is 2.
If we have:

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

This correctly specifies a Is 1, b is 2.

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

You missed Lua and/or short cut, the comma is lower in the hierarchy. Basically what is happening here is that the first 4> evaluate 5 and 1 as false, 2 or 3 as 2, and ignore 4. In the second case, 4<5 is correct, so 4<5 and 1 are 1. Leave the rest as it is. As Egor Skriptunoff suggests you do

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

Replace.

Suppose I want to assign two values ​​to two variables when a certain condition is true, and two if the condition is false Different values. I will assume it will do this:

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

However, this is specified as false and b is 2.
If we have:

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

This correctly specifies that a is 1 and b is 2.

What am I missing here, and how do I make the "ternary operator" work as I expect?

You missed the Lua and/or short cut, the comma is lower in the hierarchy. Basically what happens here is the first 4> will be 5 And 1 is evaluated as false, 2 or 3 is evaluated as 2, and 4 is ignored. In the second case, 4<5 is correct, so 4<5 and 1 are 1, and the rest remain the same. As Egor Skriptunoff suggests you

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

Replace.

Leave a Comment

Your email address will not be published.