首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Lua 判斷 Table 是否為空的最佳實踐:next() 函數

     編輯:更多程式設計知識

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  -- 遍歷所有鍵找最大整數鍵,全數字鍵表可用,混合鍵表不可靠

標準寫法:next()


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

-- 等價寫法
if not next(t) then ... end
  • next(table) 返回鍵值對的**第一個**鍵、值;空表返回 nil。
  • **不遍歷整表**,O(1) 級性能,極快。
  • **通用於所有 table**:數組、字典、混合、含 nil 值(Lua 表值不能為 nil,置 nil 即刪除鍵)。
  • Lua 5.1+ 標準庫函數,無依賴。

封裝工具函數


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 統一代碼風格,提升可讀性與正確性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved