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/