lua 元方法__newindex,实现只读的table
来源:互联网 发布:外观专利能投诉淘宝吗 编辑:程序博客网 时间:2024/06/06 19:27
lua中__newindex的调用机制跟__index (关于__index的用法参考上一篇博客点击打开链接)的调用机制是一样的,当访问table中一个不存在的key,并对其赋值的时候,lua解释器会查找__newindex元方法,如果存在,调用该方法,如果不存在,直接对原table索引进行赋值操作。
local t = {}local prototype = {}local mt = {__index = function(t,k)return prototype[k]end,__newindex = function(t,k,v)print("attempt to update a table k-v")prototype[k] = vend}setmetatable(t,mt)t[2] = "hello"print(t[2])
输出:
>attempt to update a table k-vhello
function readOnly(t)local proxy = {} --定义一个空表,访问任何索引都是不存在的,所以会调用__index 和__newindexlocal mt = {__index = t, ---__index 可以是函数,也可以是table,是table的话,调用直接返回table的索引值__newindex = function(t,k,v)error("attempt to update a read-only table",2)end}setmetatable(proxy,mt)return proxyenddays = readOnly{"Sunday","Monday","Tuesday","Wednessday","Thursday","Friday","Saturday"} print(days[1])days[2] = "hello" --这一行就非法访问了
输出:
>Sunday>: attempt to update a read-only table
0 0
- lua 元方法__newindex,实现只读的table
- lua元方法__newindex
- Lua中__newindex元方法的使用
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- Lua中的元方法__newindex详解
- lua中的元方法__index __newIndex
- lua table访问的元方法
- lua 的__newindex
- _index和__newindex元方法
- 代理的思想--实现lua中table的跟踪与只读
- 【Lua】__newindex
- Lua __newindex
- lua中设置只读table
- 读写Xml文件
- va_list实现不定参数C函数
- 使用zookeeper管理多个hbase集群
- UIButton中内容大小,以及UITextFiled改变和选中
- 【个人感悟】--做产品 & 做项目
- lua 元方法__newindex,实现只读的table
- [LeetCode] Product of Array Except Self
- po主去研究root了
- c++程序的内存格局
- HLSL编译工具—FXC
- 照顾小集期间的学习目标计划
- property标签区分字符串和OGNL表达式
- ProgressBar进度条控件
- 数据挖掘3---决策树的构造