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


根据__newindex 的这一个特性,可以用来跟踪一个table 赋值更新的操作,如果是一个只读的table ,可以通过__newindex 来实现下面是代码

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
原创粉丝点击