美文网首页
metatable 保护protected

metatable 保护protected

作者: 言之有物行之有理 | 来源:发表于2020-11-16 16:23 被阅读0次

设置元表后,填充__metatable字段,元表就无法被访问,依然可以被调用。

Set.mt = {}

Set.mt.__add = Set.union

function Set.new(t)

local set = {}

setmetatable(set,Set.mt)

for _,l in ipairs(t) do

set[l] = true

end

return set

end

Set.mt.__metatable = "not your businesss"

s1 = Set.new{}

print(getmetatable(s1))   -- 显示 not your business

setmetatable(s1,{})   -- cannot change a protected metatable

相关文章

网友评论

      本文标题:metatable 保护protected

      本文链接:https://www.haomeiwen.com/subject/aokzbktx.html