lua逻辑运算符/ a? b: c 运算符

我不理解以下代码的逻辑:

    aBoolValue = false
    ans = aBoolValue and 'yes' or 'no'
    print (ans)

'and'和'or'操作符具体是如何工作的呢?

点赞
用户3954045
用户3954045

检查布尔值

你可以使用 if 语句来检查布尔值。如果条件为真,则执行 if 后面的语句;否则,它将跳过该代码块并执行选择的其他语句。例如:

if aBoolValue == true then
  print("yes")
else
  print("no")
end

如果 aBoolValue 的值是 true,则它将打印 "yes";否则,它将打印 "no"。需要注意的是,在 Lua 中,truefalse 是全局内置变量。

参考文献:http://www.lua.org/pil/3.3.html

2014-09-24 07:21:06
用户3998938
用户3998938

考虑以下代码:

local example1 = true and "yes" or "no"
local example2 = false and "yes" or "no"

print(example1, example2) --> yes   no

如果布尔值为 true,则返回 and 后面的值。如果布尔值为 false,则返回 or 后面的值。可以这样想:

local example1 = if (true) then "yes" else "no"
--显然这段代码不会工作,但它展示了三元操作符是如何工作的
2014-09-26 00:24:08