2011-02-15 85 views
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 

当运行此脚本,我希望看到“你好”印在控制台上 - 但是,没有打印。任何人都可以解释吗?

+5

`〜=`有什么问题? – delnan 2011-02-15 16:28:55

回答

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

+1

感谢您的详细解释 – oompahloompah 2011-02-15 18:13:30

1

我没有尝试,但我觉得not==更高的优先级,从而导致

if ((not 41) == 42) then 

...明明不是运营商的结果(true或false)不等于42.

2

尝试not (gentest() == 42)。 。

0

在您的示例的上下文中,'not'不会被视为布尔值,而会被视为倒排运算符。当没有算术运算符时的布尔示例 - '如果a'表示当条件,状态,事件或开关'a'的测试满足时结果为真,'如果不是a'则意味着条件,状态,事件或开关'a'不满意。当一个条件语句有一个算术运算符和一个第二个值时,那么'不'是稍微不同的,并且该测试作为一个变量或一个文字与一个特定值相比,如'if a not = 42',因为它是一个条件运算符而不是布尔运算符和真值表可能有不同的条目。