Lua脚本中的奇怪逻辑?

前端之家收集整理的这篇文章主要介绍了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” – 但是,没有打印任何内容.有谁能解释一下?

解决方法

在while循环中,你应该使用括号外的:

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

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

(不是gentest()== 42)与((不是gentest())== 42)相同.因为gentest()不返回41 == false,你将得到false == 42,最后返回false.

猜你在找的Lua相关文章