lua只读表的实现
时间:2016-10-03 16:45:17
收藏:0
阅读:210
先上代码:
function const(t)
local temp = t --temp以upvalue的形式存储t
local ret = {}
local mt = {
__index = function(t,k)
return temp[k]
end,
__newindex = function()--空函数覆盖newindex
end
}
setmetatable(ret,mt)
return ret
end
之后可以这样用:
t = const {
SMALL= 24,
NORMAL= 30,
}
执行测试:
t.SMALL = nil --不可改变或删除成员,不会生效
t.BIG = "mmm" --不可添加成员,不会生效
print(t.SMALL,t.BIG)
输出:
24 nil
原文:http://www.cnblogs.com/leosfly/p/5929164.html
评论(0)