local a = {}
-- ❌ 錯誤:比較指標位址
if a == nil then ... end
-- ❌ 錯誤:比較匿名 table 位址
if a == {} then ... end
-- ❌ 錯誤:# 運算符要求連續整數鍵且無 nil
if #a == 0 then ... end
-- ❌ 不穩:table.maxn 依賴數字鍵最大值
if table.maxn(a) == 0 then ... end
next(t) == nillocal a = {}
if next(a) == nil then
print("table 是空的")
end
next(table) 回傳「第一組鍵值對」的鍵與值;空 table 回傳 nil。nil 值影響,通用於所有 table 結構(陣列、字典、混合)。local function is_empty(t)
return type(t) == "table" and next(t) == nil
end
-- 用法
if is_empty(config) then
config = default_config
end
Lua 判斷 table 為空,**唯一正統、通用、高效** 的方法是 next(t) == nil。棄用 #t、t == {} 等錯誤寫法,避免隱性 Bug。