元表是 Lua 賦予表「可編程語義」的核心機制。通過設置元表並定義元方法,普通表即可擁有運算符重載、繼承查找、自定義序列化、只讀保護、函數式調用等高級特性。本文系統講解元表核心概念、關鍵元方法(__index/__newindex/__add/__call/__tostring 等)、面向對象實現模式、進階應用與性能考量。
__ 開頭的函數)。setmetatable(t, mt) 將 mt 設置為 t 的元表;getmetatable(t) 獲取。一張表只能有一個元表(但可通過 __index 鏈接形成鏈)。__index —— 繼承查找與默認值的基石觸發:讀取表中不存在的鍵(t[key] 且 rawget(t, key) == nil)。
兩種形式:
__index = function(t, key) ... end。完全動態控制,可計算、委託、日誌、懶加載。__index = fallback_table。簡潔實現繼承/默認值。查找鏈:t.key → mt.__index.key → mt.__index.__index.key ...。-- 繼承鏈示例
local Base = { version = "1.0", default_config = { timeout = 1000 } }
local Derived = setmetatable({ name = "child" }, { __index = Base })
print(Derived.version) -- "1.0" (從 Base 繼承)
print(Derived.default_config.timeout) -- 1000 (嵌套表也繼承)
-- 動態計算屬性
local Proxy = setmetatable({}, {
__index = function(t, key)
if key == "time" then return os.date() end
if key:match("^get_") then return function() return key end end
return nil
end
})
print(Proxy.time) -- 當前時間
print(Proxy.get_foo()) -- "get_foo"
__newindex —— 寫入攔截與只讀/代理/脏標記觸發:賦值給表中不存在的鍵(t[key] = val 且 rawget(t, key) == nil)。已存在鍵的賦值不觸發。
__newindex = proxy_table。新鍵值對寫入代理表,原表保持不變(實現「寫時複製」或日誌記錄)。__newindex = function(t, key, val) ... end。完全控制寫入邏輯:驗證、轉換、記錄、轉發、拒絕。-- 只讀表
local function readOnly(t)
return setmetatable({}, {
__index = t,
__newindex = function(_, k, v) error("Attempt to modify read-only table: " .. k, 2) end,
__metatable = false -- 隱藏元表
})
end
local const = readOnly({ PI = 3.14159, APP_NAME = "MyApp" })
print(const.PI) -- 3.14159
-- const.PI = 3 -- error!
-- 脏標記追蹤(ORM 常用)
local function trackChanges(t)
local dirty = {}
return setmetatable(t, {
__newindex = function(t, k, v)
rawset(t, k, v)
dirty[k] = true
end,
__get_dirty = function() return dirty end
})
end
關鍵:元方法內部必須使用 rawset(t, k, v) / rawget(t, k) 避免遞歸調用自身元方法。
雙操作數元方法查找順序:第一操作數元表 → 第二操作數元表。若類型不同,優先嘗試第一個。
| 操作 | 元方法 | 示例用途 |
|---|---|---|
a + b | __add | 向量/矩陣/複數相加、集合並集 |
a - b | __sub | 向量減、集合差集 |
a * b | __mul | 矩陣乘法、字符串重複 |
a / b | __div | 向量標量除 |
a .. b | __concat | 自定義對象拼接(如 SQL 構建器) |
a == b | __eq | 值語義比較(如兩個向量坐標相等) |
a < b | __lt | 排序支援(table.sort 要求) |
a <= b | __le | 配合 __lt 實現完整比較 |
-a | __unm | 向量取反 |
#a | __len | 自定義長度語義(Lua 5.2+ 對表也生效) |
local Vec2 = {}
Vec2.__index = Vec2
function Vec2.new(x, y) return setmetatable({x=x or 0, y=y or 0}, Vec2) end
function Vec2.__add(a, b) return Vec2.new(a.x+b.x, a.y+b.y) end
function Vec2.__sub(a, b) return Vec2.new(a.x-b.x, a.y-b.y) end
function Vec2.__mul(a, b)
if type(a)=="number" then return Vec2.new(a*b.x, a*b.y) end
if type(b)=="number" then return Vec2.new(a.x*b, a.y*b) end
return a.x*b.x + a.y*b.y -- 默認點積
end
function Vec2.__tostring(v) return string.format("Vec2(%.2f, %.2f)", v.x, v.y) end
function Vec2.__eq(a, b) return a.x==b.x and a.y==b.y end
function Vec2:len() return math.sqrt(self.x^2 + self.y^2) end
function Vec2:normalize() local l=self:len(); return l>0 and Vec2.new(self.x/l, self.y/l) or Vec2.new() end
local v1, v2 = Vec2.new(3,4), Vec2.new(1,2)
print(v1 + v2) -- Vec2(4.00, 6.00)
print(v1 * 2) -- Vec2(6.00, 8.00)
print(v1 * v2) -- 11.0 (點積)
print(v1:len()) -- 5.0
__call —— 讓表像函數一樣調用觸發:t(args...) 當 t 是表且有元方法 __call。
用途:構造器語法糖、可調用對象、函數柯里化、狀態機步進。
-- 構造器語法糖
local Person = setmetatable({}, {
__call = function(cls, name, age)
return setmetatable({name=name, age=age}, {__index=cls})
end
})
local p = Person("Alice", 30) -- 相當於 Person.__call(Person, "Alice", 30)
-- 狀態機計數器
local Counter = setmetatable({count=0}, {
__call = function(t) t.count = t.count + 1; return t.count end
})
print(Counter()) -- 1
print(Counter()) -- 2
__tostring / __metatable / __gc / __mode (弱表)__tostring:print(t)/tostring(t) 時調用,返回字符串表示。調試、日誌、序列化關鍵。__metatable:設置為非 nil 值(如 false 或字符串)可隱藏元表,getmetatable(t) 返回該值,setmetatable 報錯。保護內部實現。__gc (僅 userdata/5.2+ table):垃圾回收前調用,釋放 C 資源(文件句柄、內存、鎖)。Lua 5.1 僅 userdata 支持。__mode:"k" (鍵弱引用)、"v" (值弱引用)、"kv"。實現緩存、觀察者模式無內存洩漏。local Class = {}
Class.__index = Class
function Class:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self -- 關鍵:子類元表 __index 指向自身
return o
end
local Animal = Class:new({sound="Grrr"})
function Animal:speak() print(self.sound) end
local Dog = Animal:new({sound="Woof"})
function Dog:wag() print("Wagging tail") end
local d = Dog:new{name="Buddy"}
d:speak() -- Woof (繼承)
d:wag() -- Wagging tail
print(d.name) -- Buddy
local function mixin(target, ...)
for _, src in ipairs({...}) do
for k, v in pairs(src) do
if k ~= "__index" and k ~= "__newindex" then target[k] = v end
end
end
return target
end
local Flyable = { fly = function(self) print(self.name.." flying") end }
local Swimmable = { swim = function(self) print(self.name.." swimming") end }
local Duck = mixin(Animal:new{name="Duck"}, Flyable, Swimmable)
Duck:fly(); Duck:swim()
setmetatable(config, {__index=defaults}),配置缺失自動回退默認值。__index 動態 require 子模塊並緩存。__newindex 觸發依賴更新(Vue/React 響應式核心思想原型)。__newindex 拋錯 + __metatable=false。__index/__call/__concat 組合構建聲明式 API(如 HTML 生成器、SQL Builder)。__index/__newindex,改用扁平表或預計算。__index 鏈形成環會導致棧溢出/無限循環。設計繼承鏈時保證 DAG。__mode 陷阱:鍵/值被 GC 回收後,遍歷 pairs 可能見到已回收項(需 collectgarbage() 後穩定)。__metatable = false 防止用戶誤修改破壞不變量。元表是 Lua 「機制少、威力大」哲學的集中體現。通過 __index/__newindex 實現繼承與代理,__add/__call/__tostring 實現領域建模,__mode 實現內存管理。掌握元表,即掌握了在 Lua 中構建任意高級抽象的鑰匙。下次當你寫 setmetatable 時,請記住:你正在為這張表定義一套專屬的「物理法則」。