Lua如何有条件地同时赋多个变量?

为什么这个可以

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

print(a, b) --> 1  2

但这个不行?

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

print(a, b) --> false  2

我该如何使它工作?

原文链接 https://stackoverflow.com/questions/70545748

点赞
stackoverflow用户7509065
stackoverflow用户7509065

你认为它们的工作原理是这样的(实际上这不是有效的语法):

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

但这不是它们的工作方式。它们实际上的工作方式就像你写的这样:

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

在 true 的情况下你得到了你想要的结果还只是巧合。你可以这样写,它将始终起作用:

local a, b
if false then
    a, b = 1, 2
else
    a, b = 3, 4
end
2021-12-31 22:54:44
stackoverflow用户2858170
stackoverflow用户2858170

以下是中文翻译并保留原本的 markdown 格式:

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

等价于

local a = 1 -- 因为 true and 1 是 1
local b = 2 -- 因为 2 or 3 是 2

进一步来说,

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

等价于

local a = false -- 因为 false and 1 是 false
local b = 2 -- 因为 2 or 3 是 2

这里其实没有必要使用多重赋值,因此可以简单使用

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

或者

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

另外,使用常量作为条件值并没有意义,因为它总是产生相同的结果,因此为什么不直接使用该结果呢?

2022-01-01 08:36:17