使用 and/or 运算符简化代码赋值 (lua)

我想请问是否可以简化此代码片段:

local left = true
local right = true

local xPos = 0

if left or right then
    if left and not right then
        xPos = -1
    elseif right and not left then
        xPos = 1
    else
        xPos = 0
    end
end

(当 left == true 时返回 -1,当 right == true 时返回 1,如果两者为 true 或 false 则返回 0)

在声明值本身时使用 and/or 运算符,如下所示:

local left = true
local right = true

local xPos = right and not left and 1 or -1

后一个示例的问题是它的行为与前一个示例不同,因为当两者都为 true 或 false 时它返回 -1。

如果有人能够详细解释后一个 xPos 声明的工作原理,那将不胜感激,谢谢。

点赞
用户7396148
用户7396148

Lua 处理三元运算的方式是将最后一个计算的变量赋值给它。

以你的代码为例:

local xPos = right and not left and 1 or -1

right and not lefttrue 时,你的代码段看起来像这样:

local xPos = true and 1 or -1

因为 and 语句的第一个值是 true,所以 and 语句将比较的第二个值 1 返回,or 语句因为 1 是一个 "真实的" 值,所以不会计算 -1 的结果,因此最后一个计算的变量是 1,这就是 xPos 的值。

如果你更改代码,你可以从另一个方面看到它的工作方式。

local xPos = false and 1

这里会发生什么?xPos = false。这是因为当使用 and 时,如果第一个条件是 false,Lua 将不会继续计算,这意味着最后一个计算的变量是 false,所以 xPos = false

2019-01-30 15:29:01