看过lua的文档中有个说明,
“Tables and full userdata have individual metatables (although multiple tables and userdata can share their metatables). Values of all other types share one single metatable per type; that is, there is one single metatable for all numbers, one for all strings, etc.“
table和fulluserdata有独立的元表。其他类型每个类型共享一个metatable,比如numbers或者strings。
local mt = debug.getmetatable(0) or {}
--修改函数调用元方法
mt.__call = function(a,b)
local t = {}
for _=a,b do
table.insert(t,_)
end
return unpack(t)
end
debug.setmetatable(0,mt)
print((3)(5)) --输出3 4 5
由此可见number类型数据共享一个metatable,同理可以查看到字符串也共享一个metatable
local mt = debug.getmetatable("") or {}
mt.__call = function(a,b)
return a .. b
end
debug.setmetatable("",mt)
print(("ab")("cd")) --输出abcd









网友评论