萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Lua 判斷 Table 是否為空:next() 是唯一正解

錯誤嘗試史

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) == nil

local a = {}
if next(a) == nil then
    print("table 是空的")
end

原理解析

  • next(table) 回傳「第一組鍵值對」的鍵與值;空 table 回傳 nil。
  • 不依賴鍵型別、不要求連續、不受 nil 值影響,通用於所有 table 結構(陣列、字典、混合)。
  • 效能 O(1),僅需哈希表/陣列內部指標檢查。

封裝工具函式

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。

copyright © 萬盛學電腦網 all rights reserved