在 Lua 中,它是如何处理的?(只显示翻译内容)

我在 Lua 风格指南 中看到了以下代码:

print(x == "yes" and "YES!" or x)

上下文:

local function test(x)
  print(x == "yes" and "YES!" or x)
  -- 不用 if x == "yes" then print("YES!") else print(x) end
end

" x == "yes" and "YES!" " 到底会发生什么?为什么会打印出 "YES!" 或 (x) 而不是 "true" 或 (x)?

编辑:

这是什么意思:

X == "yes"               -- > true
true and (value)         -- > value
print( (x == "yes") and value)

所以检查 x 是否为值 "yes" 会返回 true,将 true 添加到值中会返回该值,并打印该过程会打印该值,对吗?

点赞
用户4323
用户4323

根据 Lua 官方文档中的3.3节,我们可以得出以下结论:

运算符 and 如果第一个参数是 false 或 nil,则返回第一个参数;否则返回第二个参数。

因此,true and "YES!" 的结果为 "YES!"

这个规则可以成立的原因是,如果第一个参数为假值,整个表达式将变为假值(与第一个参数一致);否则,它将与第二个参数相同,如果第二个参数为真值,则会使整个表达式成为真值。

2015-01-16 06:38:01