lua中实现对一个表的监控

监控内容:访问表中的元素和更新表中的元素

代码:

 1 local index = {}
 2 
 3 --注意:元表也是表,其中的元素也需要用合理分隔符分开
 4 local mt = 
 5 {
 6     __index = function(t,k)
 7         print("访问元素:" .. tostring(k));
 8         return t[index][k];
 9     end,
10 
11     __newindex = function(t,k,v)
12         print("更新元素: k = ".. tostring(k) .. ", v = " ..tostring(v));
13         t[index][k] = v;
14     end
15 }
16 
17 
18 function Track(t)
19     local proxy = {};
20     proxy[index] = t;
21     setmetatable(proxy,mt);
22     return proxy;
23 end

测试用例:

1 local tab = {a = 12};
2 tab = Track(tab);
3 tab["a"] = 13
4 print(tab["a"])

输出结果:

猜你喜欢

转载自www.cnblogs.com/luguoshuai/p/13174346.html