Lua 中的 if 语句风格不能正确返回布尔值

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

当值为 true 时返回正确的 boolean,但是当值为 false 时出错。为什么?

点赞
用户415823
用户415823

布尔运算习惯用法通过使用短路求值(只在必要时才计算第二个操作数)来实现。

如果使用显式优先级重写表达式,您将看到为什么会得到 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

Programming in Lua 中的 Logical Operators 部分解释了这种习惯用法:

另一个有用的习惯用法是 (a and b) or c(或者只是 a and b or c,因为 and 的优先级高于 or),它等价于 C 表达式

a ? b : c

前提是 b 不为假。例如,我们可以使用如下语句选择两个数 x 和 y 的最大值

max = (x > y) and x or y

为什么 b 不能为 false?因为计算永远会返回 false

1 > 0 and false  --> false
1 < 0 and false  --> false
2016-08-02 22:08:49