Lua,if 语句惯用法未能返回正确的 bool 值

标签 lua

local a = (true==true) and false or nil -- returns nil
local a = (true==true) and true or nil -- returns true
local a = (true==true) and not false or nil -- returns true
local a = (true==true) and not true or nil -- returns nil

当值为 true 时返回正确的 boolean,但当 false 时返回失败。为什么?

最佳答案

bool 习惯用法通过使用快捷求值来工作(仅在必要时求值第二个操作数)。

如果您以明确的优先级重写表达式,您就会明白为什么会得到nil:

(true and false) or nil     =>  false or nil  => nil
(true and true) or nil      =>  true or nil   => true
(true and not false) or nil =>  true or nil   => true
(true and not true) or nil  =>  false or nil  => nil

Logical Operators Programming in Lua 部分解释这个成语:

Another useful idiom is (a and b) or c (or simply a and b or c, because and has a higher precedence than or), which is equivalent to the C expression

a ? b : c

provided that b is not false. For instance, we can select the maximum of two numbers x and y with a statement like

max = (x > y) and x or y

为什么b不能为false?因为计算总是返回 false

1 > 0 and false  --> false
1 < 0 and false  --> false

关于Lua,if 语句惯用法未能返回正确的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38730534/

相关文章:

c++ - 如何检查传递给 Lua 的参数是否是用户定义的类型?

lua - 使用lua模拟登录

http - 将 stdout 流式传输到网页

c++ - 如何使用 luajit 在带有变量参数的 c 函数中获取 cdata?

lua - lua有像python的slice这样的东西吗

function - 在Lua中,如何正确地将nil参数设置为某个默认值?

lua - 静态分析 Lua 代码以查找潜在错误

lua - Lua 脚本调用 C 共享库的最佳方式?

共享对象的lua加载路径

lua - 在变量赋值中处理可变参数值的惯用方法是什么?