Lua 是動態強類型語言,**值有類型,變量無類型**。type() 是判斷值類型的唯一標準函數,返回類型名稱字符串。本文詳細列舉 Lua 八大基本類型特性與判斷用法。
a = type(X) -- a = "nil" (若 X 未定義)
b = type(a) -- b = "string" (type() 返回值永遠是字符串)
a = type(nil) -- a = "nil"
"nil"、"number"、"string"、"boolean"、"table"、"function"、"userdata"、"thread"。"int"、"float" 區分(Lua 5.3+ 內部區分整數/浮點,type() 仍返回 "number",用 math.type() 區分)。true 和 false。**只有 nil 和 false 為假**,0、空字符串、空表均為真。type() 統一返回 "number"。[[...]]。coroutine.create/resume/yield 協作式調度。
-- ❌ 錯誤:比較 table 引用
if my_table == {} then ... end -- 永遠 false,{} 創建新表
-- ✅ 正確:判斷 table 是否為空
if next(my_table) == nil then ... end -- 標準寫法
-- ✅ 判斷數字(含字符串數字)
local n = tonumber(val)
if n then ... end
-- ✅ 判斷函數
if type(callback) == "function" then callback() end
type() 返回字符串是類型檢查的基石。理解八大類型語義——特別是 **nil/boolean 假值規則**、**string 字節序列特性**、**table 唯一結構地位**、**function 第一類值**、**thread 協程非線程**——是編寫正確、高效、可嵌入 Lua 代碼的前提。