前置知识: Lua

元表与元方法详解

1 minAdvanced2026/6/14

Lua元表与元方法详解:__index、__newindex、__call、__tostring。

1. 元表基础

local t = {}
local mt = {
    __index = function(table, key)
        return "default:" .. key
    end
}
setmetatable(t, mt)

print(t.hello)  -- "default:hello"

2. 常用元方法

元方法触发时机
__index访问不存在的键
__newindex设置不存在的键
__call将表当作函数调用
__tostringtostring() 转换
__add+ 运算
__sub- 运算
__mul* 运算
__eq== 运算
__lt< 运算
__len# 运算
__pairspairs() 迭代

3. __index 实现继承

local Animal = { speak = function(self) return "..." end }

local Dog = setmetatable({}, { __index = Animal })
Dog.speak = function(self) return "Woof!" end

local d = setmetatable({}, { __index = Dog })
print(d:speak())  -- "Woof!"

4. __call

local counter = setmetatable({ count = 0 }, {
    __call = function(self, increment)
        self.count = self.count + (increment or 1)
        return self.count
    end
})

counter(1)    -- 1
counter(5)    -- 6

5. __tostring

local person = setmetatable({ name = "Alice", age = 30 }, {
    __tostring = function(self)
        return string.format("%s (%d)", self.name, self.age)
    end
})

print(person)  -- "Alice (30)"