Lua 中 table 既是數組又是字典,**判斷「空 table」即 {}** 是高頻需求。本文對比多種寫法,確立 next(t) == nil 為標準最佳實踐。
-- ❌ 錯誤:比較引用地址
if t == nil then ... end -- t 是引用,永不為 nil (除非賦 nil)
if t == {} then ... end -- {} 創建新表,地址不同,永遠 false
-- ❌ 有陷阱:# 操作符
if #t == 0 then ... end -- # 要求數組部分連續且無 nil 空洞,字典鍵不計入
-- ⚠️ 不穩:table.maxn()
if table.maxn(t) == 0 then ... end -- 遍歷所有鍵找最大整數鍵,全數字鍵表可用,混合鍵表不可靠
local t = {}
if next(t) == nil then
print("table 是空的")
end
-- 等價寫法
if not next(t) then ... end
next(table) 返回鍵值對的**第一個**鍵、值;空表返回 nil。
function is_empty_table(t)
return type(t) == "table" and next(t) == nil
end
-- 用法
if is_empty_table(config) then
load_defaults()
end
**next(t) == nil 是判斷 Lua 空 table 的唯一正統寫法**。拒絕 #t、t == {}、table.maxn 等陷阱寫法。封裝 is_empty_table 統一代碼風格,提升可讀性與正確性。