Lua脚本中的奇怪逻辑?
我似乎无法理解Lua计算布尔值的方式 下面是一个小片段,旨在演示问题:Lua脚本中的奇怪逻辑?,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_he
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
函数foo()
返回真值
结束
函数gentest()
返回41
结束
函数print_hello()
打印('你好')
结束
idx=0
而(idx<10)do
如果foo()那么
如果(不是最优雅的()==42),那么
打印_hello()
结束
结束
idx=idx+1
结束
当这个脚本运行时,我希望看到控制台上打印“Hello”——但是,没有打印任何内容。有人能解释一下吗 我没有尝试这个,但我认为
not
的优先级高于=
,导致
if ((not 41) == 42) then
。。。显然not运算符的结果(true或false)不等于42。尝试
not(gentest()==42)
在while循环中,应使用括号外的not
:
while (idx < 10) do
if foo() then
if not (gentest() == 42) then
print_hello()
end
end
idx = idx +1
end
while(idx<10)do
如果foo()那么
如果不是(gentest()==42),则
打印_hello()
结束
结束
idx=idx+1
结束
(gentest()==42)
将返回false,然后非false
将返回true
(not gentest()==42)
与(not gentest())==42)
相同。由于not gentest()
返回not 41
=false
,您将得到false==42
,最后返回false在本例的上下文中,“not”将不会被视为布尔运算符,而是作为反向运算符。无算术运算符时的布尔示例-“如果a”表示满足条件、状态、事件或开关“a”的测试时结果为真,“如果a”表示不满足条件、状态、事件或开关“a”时结果为真。当一个条件语句有一个算术运算符和一个第二个值时,则“not”略有不同,测试针对的是一个特定值作为变量或文字,如“if a not=42”,因为它是一个条件运算符而不是布尔运算符,真值表可能有不同的条目