如何让 __metatable 函数被调用?
How to get __metatable function to be called?
我的目标
获取 getmetatable
到 return 分配给 __metatable
字段的函数的 return 值。
代码:
local x, m = {}, {__metatable = function() return nil end};
setmetatable(x, m);
io.write("Let's get the metatable:", tostring(getmetatable(x)), "\n");
但我得到的是实际函数而不是 return。
那么我如何调用它才能得到 nil 呢?所以它好像没有元表?
只需重写 getmetatable 以按照您希望的方式工作;)
do local getmetatable = getmetatable
function _G.getmetatable(tab)
local meta = getmetatable(tab)
if type(meta)=='function' then
return meta(tab)
else
return meta
end
end
end
或者,您可以将 __metatable
设置为 false。这适用于像 if getmetatable(foo) then
这样编写的代码,但会破坏像 if getmetatable(foo) == false
这样的代码。可以说,第一个是你应该使用的那个,但可能有人在做第二个。
这也会向用户暗示 是 一个元表,他们 none 只是忙着弄乱它。
我的目标
获取 getmetatable
到 return 分配给 __metatable
字段的函数的 return 值。
代码:
local x, m = {}, {__metatable = function() return nil end};
setmetatable(x, m);
io.write("Let's get the metatable:", tostring(getmetatable(x)), "\n");
但我得到的是实际函数而不是 return。
那么我如何调用它才能得到 nil 呢?所以它好像没有元表?
只需重写 getmetatable 以按照您希望的方式工作;)
do local getmetatable = getmetatable
function _G.getmetatable(tab)
local meta = getmetatable(tab)
if type(meta)=='function' then
return meta(tab)
else
return meta
end
end
end
或者,您可以将 __metatable
设置为 false。这适用于像 if getmetatable(foo) then
这样编写的代码,但会破坏像 if getmetatable(foo) == false
这样的代码。可以说,第一个是你应该使用的那个,但可能有人在做第二个。
这也会向用户暗示 是 一个元表,他们 none 只是忙着弄乱它。