2011-02-15 81 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',因爲它是一個條件運算符而不是布爾運算符和真值表可能有不同的條目。