布爾我碰到一個錯誤: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
是什麼原因導致這個錯誤?謝謝。
布爾我碰到一個錯誤: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
是什麼原因導致這個錯誤?謝謝。
0 < x < 128
相當於(0 < x) < 128)
,因此是錯誤消息。
寫測試爲0 < x and x < 128
。
寫作0 < x < 128
在Python中是可以的,但在Lua中沒有。
所以,當你的代碼被執行時,Lua會首先計算是否0 < x
是true
。如果屬實,則比較結果變爲true < 128
,這顯然是錯誤消息的原因。
要使其工作,你必須寫:
if x < 128 and x > 0 then
--do something
end