Lua脚本中的奇怪逻辑?

oom*_*pah 3 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
Run Code Online (Sandbox Code Playgroud)

运行此脚本时,我希望在控制台上看到"Hello" - 但是,没有打印任何内容.有谁能解释一下?

Fáb*_*rez 10

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

while (idx < 10) do
 if foo() then
    if not (gentest() == 42) then
       print_hello()
    end
 end
 idx = idx +1
end
Run Code Online (Sandbox Code Playgroud)

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

(not gentest() == 42)是一样的( (not gentest()) == 42).因为not gentest()return not 41== false,你会得到false == 42,最后返回false.