Lua脚本中的奇怪逻辑?

3

我似乎无法理解 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”打印出来,但是什么也没有打印。有人能解释一下吗?
4个回答

10

在 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


2
尝试使用not (gentest() == 42)进行操作。

1

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

if ((not 41) == 42) then

显然,非运算符的结果(无论是真还是假)都不等于42。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接