在Lua脚本中有奇怪的逻辑?

我似乎不能理解Lua计算布尔值的方式。

这是一个用于演示问题的微不足道的片段:

function foo()
  return true
end

function gentest()
   return 41
end

function print_hello()
  print ('Hello')
end

idx = 0

while (idx < 10) do
 if foo() then
    if (not gentest() == 42) then
       print_hello()
    end
 end
 idx = idx +1
end

当运行该脚本时,我期望在控制台上看到“Hello”打印出来,但实际上没有任何东西被打印出来。有人可以解释一下吗?

原文链接 https://stackoverflow.com/questions/5006085

点赞
stackoverflow用户600500
stackoverflow用户600500

我没有尝试过这个,但我认为 not== 有更高的优先级,导致以下结果:

if ((not 41) == 42) then

...很明显,not 操作符的结果(true 或 false)与 42 不相等。

2011-02-15 16:09:53
stackoverflow用户107090
stackoverflow用户107090

尝试not (gentest() == 42)

2011-02-15 16:10:21
stackoverflow用户604734
stackoverflow用户604734

在 while 循环中,应该在括号外使用 not

while (idx < 10) do
  if foo() then
    if not (gentest() == 42) then
      print_hello()
    end
  end
  idx = idx + 1
end

(gentest() == 42) 返回 false,然后 not false 返回 true。

(not gentest() == 42)( (not gentest()) == 42) 相同。因为 not gentest() 返回 not 41 == false,所以你将得到 false == 42,最终返回 false

2011-02-15 16:10:36
stackoverflow用户571539
stackoverflow用户571539

在您的示例上下文中,“not” 不会被视为布尔运算符,而是被视为反转运算符。例如布尔运算符,当没有算术运算符时,“if a” 表示当条件、状态、事件或开关“a” 的测试满足时结果为真,“if not a” 表示当条件、状态、事件或开关“a” 不满足时结果为真。当一个条件语句有一个算术运算符和第二个值时,“not” 会略有不同,测试针对一个特定的变量或字面值作为一个值,例如 “if a not = 42”,因为它是一个条件运算符而不是布尔运算符,真值表可能有不同的条目。

2011-02-20 17:07:25