菜鸟教程 https://www.runoob.com/lua/lua-metatables.html
Lua 提供了元表(Metatable),允许我们改变table的行为,每个行为关联了对应的元方法。
例如,使用元表我们可以定义Lua如何计算两个table的相加操作a+b。
setmetatable(table,metatable): 对指定 table 设置元表(metatable),如果元表(metatable)中存在 __metatable 键值,setmetatable 会失败
__index、__newindex、__add、__call、__tostring的实际使用
mytable = {1, 2, 3}
metatable_index = {}
my_metatable = {
-- __index通过键来访问 table 的时候,如果这个键没有值,那么Lua就会寻找该table的metatable(假定有metatable)中的__index 键。如果__index包含一个表格,Lua会在表格中查找相应的键。
__index = function(tab, key)
print(key)
return 1
end,
-- __newindex 元方法用来对表更新。当你给表的一个缺少的索引赋值,解释器就会查找__newindex 元方法:如果存在则调用这个函数而不进行赋值操作
-- __newindex为函数或者表,作用不一
--__newindex = function(tab, key, val)
-- print("设置的key为:", key)
-- rawset(tab, key, val)
--end,
__newindex = metatable_index,
-- __add tableA + tableB时候触发
__add = function(tb1, tb2)
local new_tb = {}
for k, v in pairs(tb1) do
new_tb[#new_tb + 1] = {k, v}
end
for k, v in pairs(tb2) do
new_tb[#new_tb + 1] = {k, v}
end
return new_tb
end,
-- __call 当我们把表当成函数一样调用的时候,会调用__call的function
__call = function(tab, arg1, arg2, arg3)
print("__call ", arg1)
end,
-- __tostring元方法用于修改表的输出行为
__tostring = function(mytable)
sum = 0
for k, v in pairs(mytable) do
sum = sum + v
end
return "表所有元素的和为 " .. sum
end,
}
setmetatable(mytable, my_metatable)
-- __index
print(mytable[6], metatable_index[6])
-- __newindex
mytable[6] = 3
print(mytable[6], metatable_index[6])
-- __add
a = {1, 2, 3}
setmetatable(a, my_metatable)
b = {4, 5, 6}
new_tb = a + b
for k, v in next, new_tb do
print(k, v[1], v[2])
end
-- __call
mytable(3)
-- __tostring
print(mytable)
原文:https://www.cnblogs.com/orxx/p/10839823.html