lua只读表的实现

先上代码:

 1 function const(t)
 2   local temp = t --temp以upvalue的形式存储t
 3   local ret = {}
 4   local mt = {
 5     __index = function(t,k)
 6       return temp[k]
 7     end,
 8     __newindex = function()--空函数覆盖newindex
 9       
10     end,
11 
12     __metatable = false,
13   }
14   setmetatable(ret,mt)
15   return ret
16 end

 

之后可以这样用:

 1 t = const {
 2 
 3   SMALL= 24,
 4 
 5   NORMAL= 30,
 6 
 7 }
 8 
 9  
10 
11 --执行测试:
12 
13 t.SMALL = nil  --不可改变或删除成员,不会生效
14 t.BIG = "mmm" --不可添加成员,不会生效
15 print(t.SMALL,t.BIG)
16 
17 --输出:24  nil

 

posted on 2016-10-03 15:22  飞天里欧斯  阅读(438)  评论(0编辑  收藏  举报

导航