元表是普通的Lua表,定义了原始值在某些特定操作下的行为。
我们称元表中的键为事件,称值为元方法。
设置(SetMetatable)/获取(GetMetatable)元表:
SetMetatable 的两种写法:
local mt = {}
setMetatable(t, mt)setMetatable(t, {__add = function() end})
local mt = {}
local t = {}
print(getmetatable(t)) // nil
setmetatable(t, mt) // 设置表 t 的元表为 mt
print(mt)
print(getmetatable(t)) // 获取元表地址 和上面打印的 mt 地址相同
输出结果:
nil
table: 000001ECD17E3940
table: 000001ECD17E3940
local mt = {}mt.__add = function(tab1, tab2)local resTab = {}local len = math.max(#tab1, #tab2)if len == 0 then return resTab endfor i = 1, len, 1 doif type(tab1[i]) == "nil" then tab1[i] = 0 endif type(tab2[i]) == "nil" then tab2[i] = 0 endresTab[i] = tab1[i] + tab2[i]endreturn resTab
endlocal tab1 = {1, 2, 3}
local tab2 = {4, 5, 6}setmetatable(tab1, mt)
setmetatable(tab2, mt)local resTab = tab1 + tab2for index, value in ipairs(resTab) doprint(value)
end
输出结果:
5
7
9
元方法 | 对应运算符 |
---|---|
__add | + |
__sub | - |
__mul | * |
__div | / |
__mod | % |
__concat | …(连接符) |
__eq | == |
__lt | < |
__le | <= |
当涉及二元操作符时:两表元表有以下情况
local mt1 = {}
local mt2 = {}mt1.__sub = function(t1,t2)print("mt1->sub")
endmt2.__sub = function(t1,t2)print("mt2->sub")
endlocal t1 = {}
local t2 = {}
local t3 = {}setmetatable(t1,mt1) -- 设置mt1为t1(普通表)的元表
setmetatable(t2,mt2) -- 设置mt2为t2(普遍表)的元表local res1 = t1 - t2 -- 计算过程中调用元表的mt1.__sub元方法 mt1->sublocal res2 = t2 - t1 -- 计算过程中调用元表的mt2.__sub元方法 mt2->sublocal res3 = t3 - t1 -- 由于t3没有元表 __sub元方法,所以调用t1的元表中的元方法 mt1->sub
local mt = {}mt.__tostring = function(tab)local str = ""for index, value in pairs(tab) dostr = str .. index .. "--" .. value .. "\n"endreturn str
endlocal tab = {1, 2, 3}setmetatable(tab, mt)print(tab)
输出结果:
1--1
2--2
3--3
1. __index 是一个表
local mt = {}
mt.__index = {sex = "boy"}local tab = {name = "ming", age = 18}print(tab.name, tab.age) -- ming 18
print(tab.sex) -- nilsetmetatable(tab, mt)print(tab.sex) -- boy
print(tab.enjoy) -- nil
2. __index 是一个函数
local mt = {}
mt.__index = function(table,key)print(table) -- 打印t表print(key) -- 打印name
endlocal t = {}
setmetatable(t,mt)print(t.name) -- t表不可以找到,调用元表的 __index 元方法
输出结果:
table: 0000026EFEE9F4C0
name
nil
1. 普通表修改键值
存在则修改,不存在就会增加
local t = {name = "Y"}
t.name = "YY" -- 修改
t.age = 23 -- 添加for key , value in pairs(t) do --无序遍历字典类型表print(key .. " : " .. value)
end
输出结果:
age : 23
name : YY
2.__newindex是一个函数
调用_newindex函数,但是不会给元表赋值
local mt = {}mt.__newindex = function(table, key, value)print(table)print("key:" .. key)print("value:" .. value)endlocal t = {}
setmetatable(t,mt)print(t.name) -- nil
t.name = "YY"
print(t.name) -- 赋值后 先调用__newindex函数然后打印 nil
输出结果:
nil
table: 0000012C2529F5F0
key:name
value:YY
nil
3.__newindex是一个表
如果普通表没有该变量,那么到元表查找,并在元表新增或修改变量值
local k = {name = "ming"}
local mt ={}
mt.__newindex = klocal t = {}
setmetatable(t,mt)
print(t.name) -- nil 查询
print(k.name) -- Y 查询t.name = "YY" -- 到对应的k表 修改
print(k.name) -- YY 查询
print(t.name) -- nil 查询
输出结果:
nil
ming
YY
nil