Lua if 陳述式根據布林表達式決定是否執行區塊。Lua 的真假判定規則獨特:只有 false 和 nil 為假,數值 0、空字串 ""、空表 {} 皆為真。
if condition then
-- 條件為真時執行
end
a = 10
if a < 20 then
print("a is less than 20")
end
print("value of a is:", a)
a is less than 20
value of a is: 10
| 值 | 布林語境結果 |
|---|---|
false | 假 |
nil | 假 |
0 | 真 |
"" | 真 |
{} | 真 |
| 非空字串/表/數值/函數/執行緒/userdata | 真 |
local v = 0
if v then print("v 是真") end -- 會印出,因為 0 為真
if v == 0 then print("v 等於 0") end -- 正確判斷數值零