Lua how can I assign multiple variables at once conditionally?

891 Views Asked by At

Why does this work

local a, b =
  true
  and 1, 2
   or 3, 4

print(a, b) --> 1  2

but this doesn't?

local a, b =
  false
  and 1, 2
   or 3, 4

print(a, b) --> false  2

how can I make it work?

2

There are 2 best solutions below

0
Joseph Sible-Reinstate Monica On

You appear to think these work something like this (not actually valid syntax):

local a, b = true and (1, 2) or (3, 4)
local a, b = false and (1, 2) or (3, 4)

But that's not how they work. They really work as if you wrote this:

local a, b = (true and 1), (2 or 3), 4
local a, b = (false and 1), (2 or 3), 4

It's only by coincidence that you got the result you wanted in the true case. You could write something like this instead, which will work all the time:

local a, b
if false then
    a, b = 1, 2
else
    a, b = 3, 4
end
0
Piglet On
local a, b = true and 1, 2 or 3, 4

is equivalent to

local a = 1 -- because true and 1 is 1
local b = 2 -- because 2 or 3 is 2

Further

local a, b = false and 1, 2 or 3, 4

is equivalent to

local a = false -- because false and 1 is false
local b = 2 -- because 2 or 3 is 2

There is no actual need to use multiple asignment here. So simply use

local a = condition and 1 or 3
local b = condition and 2 or 4

or

local a, b
if condition then
  a, b = 1, 2
else
  a, b = 3, 4
end

Also there is no point in using a constant as your condition value. It will always yield the same result so why not use that result right away.