元表与元方法详解
00:00
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 | 将表当作函数调用 |
| __tostring | tostring() 转换 |
| __add | + 运算 |
| __sub | - 运算 |
| __mul | * 运算 |
| __eq | == 运算 |
| __lt | < 运算 |
| __len | # 运算 |
| __pairs | pairs() 迭代 |
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)"