2015-04-15 33 views
4

布爾我碰到一個錯誤:attempt to compare boolean with number用下面的代碼:的Lua:嘗試比較數

local x = get_x_from_db() -- x maybe -2, -1 or integer like 12345 
if 0 < x < 128 then 
    -- do something 
end 

是什麼原因導致這個錯誤?謝謝。

回答

3

0 < x < 128相當於(0 < x) < 128),因此是錯誤消息。

寫測試爲0 < x and x < 128

7

寫作0 < x < 128在Python中是可以的,但在Lua中沒有。

所以,當你的代碼被執行時,Lua會首先計算是否0 < xtrue。如果屬實,則比較結果變爲true < 128,這顯然是錯誤消息的原因。

要使其工作,你必須寫:

if x < 128 and x > 0 then 
    --do something 
end