首页 > 其他 > 详细

lua只读表的实现

时间:2016-10-03 16:45:17      阅读:209      评论:0      收藏:0      [点我收藏+]

先上代码:

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

lua只读表的实现

原文:http://www.cnblogs.com/leosfly/p/5929164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!