__index和__newindex都是在只有表中访问的域不存在的时候才起作用。捕获对一个表的所有访问情况的唯一方法是保持表为空。所以想监控一个表的所有访问情况,我们就应该创建一个代理,这个代理是空表。
local index = {}
local mt = {
__index = function(t, k)
print("*access to element "..tostring(k))
return t[index][k]
end,
__newindex = function (t,k,v)
print("*update of element "..tostring(k).." to "..tostring(v))
t[index][k] = v
end
}
function trace(t)
local proxy = {} --代理
proxy[index] = t
setmetatable(proxy, mt)
return proxy
end
我们想监控表的话,要做的只是 t=trace(t)