如果转载,请注明博文来源:http://www.cnblogs.com/vanishfan/p/6909153.html  望各位支持!

项目中部分只读表易被人误改写,故决定在非线上环境里对这些表附加只读属性,方便在出现误改写的时候抛出lua错误,最终版代码如下:

 --[[------------------------------------------------------------------------------
-** 设置table只读 出现改写会抛出lua error
-- 用法 local cfg_proxy = read_only(cfg) retur cfg_proxy
-- 增加了防重置设置read_only的机制
-- lua5.3支持 1)table库支持调用元方法,所以table.remove table.insert 也会抛出错误,
-- 2)不用定义__ipairs 5.3 ipairs迭代器支持访问元方法__index,pairs迭代器next不支持故需要元方法__pairs
-- 低版本lua此函数不能完全按照预期工作
*]]
function read_only(inputTable)
local travelled_tables = {}
local function __read_only(tbl)
if not travelled_tables[tbl] then
local tbl_mt = getmetatable(tbl)
if not tbl_mt then
tbl_mt = {}
setmetatable(tbl, tbl_mt)
end local proxy = tbl_mt.__read_only_proxy
if not proxy then
proxy = {}
tbl_mt.__read_only_proxy = proxy
local proxy_mt = {
__index = tbl,
__newindex = function (t, k, v) error("error write to a read-only table with key = " .. tostring(k)) end,
__pairs = function (t) return pairs(tbl) end,
-- __ipairs = function (t) return ipairs(tbl) end, 5.3版本不需要此方法
__len = function (t) return #tbl end,
__read_only_proxy = proxy
}
setmetatable(proxy, proxy_mt)
end
travelled_tables[tbl] = proxy
for k, v in pairs(tbl) do
if type(v) == "table" then
tbl[k] = __read_only(v)
end
end
end
return travelled_tables[tbl]
end
return __read_only(inputTable)
end

测试代码如下:

 local t0 = {k = }
local t2 = {
fdsf = {}
}
local t1 = {
a = {, },
b = {,ddss = , t2 = t2},
d = ,
e = "string",
}
t1.c=t1 local t3 = read_only(t1) print(t3.d, t3.c.e, t3.c.c.b.t2.fdsf)
function q1() t3.d = end
function q2() t3.c.d = end
function q3() t3.c.c.b.t2.fdsf = end
function q4() table.remove(t3.a) end
function q5() t3.b[ddss] = nil end
function q6() t3[f] = end
function q7() table.insert(t3.a, ) end print(pcall(q1))
print(pcall(q2))
print(pcall(q3))
print(pcall(q4))
print(pcall(q5))
print(pcall(q6))
print(pcall(q7))
print(t3.a[])
for k,v in pairs(t3) do
print("===pairs t3:",k,v)
end
for k,v in pairs(t3.a) do
print("===pairs t3.a:",k,v)
end
for k,v in ipairs(t3) do
print("===ipairs t3:",k,v)
end
for k,v in ipairs(t3.a) do
print("===ipair t3.a",k,v)
end
print("len t3:",#t3)
print("len t3.a:", #t3.a) local t4 = read_only(t2) local t5 = read_only(t0)
local t6 = read_only(t0) print(t3.b.t2, read_only(t2))
print(t5, t6, t0)

测试环境https://www.lua.org/cgi-bin/demo  lua5.3.4:

    string    table: 0x20d4ba0
false input:: error write to a read-only table with key = d
false input:: error write to a read-only table with key = d
false input:: error write to a read-only table with key = fdsf
false input:: error write to a read-only table with key =
false input:: error write to a read-only table with key = nil
false input:: error write to a read-only table with key = nil
false input:: error write to a read-only table with key = ===pairs t3: e string
===pairs t3: b table: 0x20ccd60
===pairs t3: a table: 0x20d4e70
===pairs t3: d
===pairs t3: c table: 0x20ca700
===pairs t3.a:
===pairs t3.a:
===ipair t3.a
===ipair t3.a
len t3:
len t3.a:
table: 0x20d4870 table: 0x20d4870
table: 0x20d5690 table: 0x20d5690 table: 0x20d1140

代码思路设计:

1.使用proxy={}空表而不是目标表tbl来设置__newindex是因为__newindex必须在原表里面不存在才会调用,这样就依然可以对已存在的字段进行改写

__newindexThe indexing assignment table[key] = value. Like the index event, this event happens when table is not a table or when key is not present in table. The metamethod is looked up in table.

Like with indexing, the metamethod for this event can be either a function or a table. If it is a function, it is called with tablekey, and value as arguments. If it is a table, Lua does an indexing assignment to this table with the same key and value. (This assignment is regular, not raw, and therefore can trigger another metamethod.)

Whenever there is a __newindex metamethod, Lua does not perform the primitive assignment. (If necessary, the metamethod itself can call rawset to do the assignment.)

2.避免出现table的互相引用,加入travelled_tables存储已经设置过proxy的table的映射

3.对于原表tbl的访问使用__index=tbl

4.对于表查长度使用__len= function () return #tbl end

5.对于遍历pairs,查到lua5.3的pairs默认迭代器next不支持访问元表__index,故直接__pairs = function () return pairs(tbl) end,以此来生成对目标表的迭代遍历

6.对于ipairs,查到lua5.3 ipairs函数生成的迭代器默认就支持访问元表__index,故不需要添加__ipairs

8.2 – Changes in the Libraries

  • The ipairs iterator now respects metamethods and its __ipairs metamethod has been deprecated.

7.对于table.insert , table.remove不用特殊处理,lua5.3的table lib支持元表操作,故依然会抛错

8.2 – Changes in the Libraries

  • The Table library now respects metamethods for setting and getting elements.

8.避免重复创建read_only,每个tbl只创建一个proxy代理,在tbl的metatable里和proxy的metatable里都设置属性__read_only_proxy,可以直接访问获得

Lua 设置table为只读属性的更多相关文章

  1. lua的table表处理 及注意事项

    lua,一款很轻量级很nice很强大的脚本语言,做为lua中使用最为频繁的table表,在使用之时还是有颇多的好处与坑的: 下面是大牛 云风的一片关于lua table的blog,可使得对lua ta ...

  2. Lua 之table库

    标准table库 table.concat(table, sep,  start, end) concat是concatenate(连锁, 连接)的缩写,table.concat()函数列出参数中指定 ...

  3. lua weak table 概念解析

    lua weak table 经常看到lua表中有 weak table的用法, 例如: weak_table = setmetatable({}, {__mode="v"}) 官 ...

  4. lua中 table 元表中元方法的重构实现

    转载请标明出处http://www.cnblogs.com/zblade/ lua作为游戏的热更新首选的脚本,其优势不再过多的赘述.今天,我主要写一下如何重写lua中的元方法,通过自己的重写来实现对l ...

  5. lua中 table 重构index/pairs元方法优化table内存占用

    转载请标明出处http://www.cnblogs.com/zblade/ lua作为游戏的热更新首选的脚本,其优势不再过多的赘述.今天,我主要写一下如何重写lua中的元方法,通过自己的重写来实现对l ...

  6. lua的table元类

    Lua中提供的元表是用于帮助Lua数据变量完成某些非预定义功能的个性化行为,如两个table的相加.假设a和b都是table,通过元表可以定义如何计算表达式a+b.当Lua试图将两个table相加时, ...

  7. lua 的 table 处理

    lua 的整体效率是很高的,其中,它的 table 实现的很巧妙为这个效率贡献很大. lua 的 table 充当了数组和映射表的双重功能,所以在实现时就考虑了这些,让 table 在做数组使用时尽量 ...

  8. 打印Lua的Table对象

    小伙伴们再也不用为打印lua的Table对象而苦恼了, 本人曾也苦恼过,哈哈 不过今天刚完成了这个东西, 以前在网上搜过打印table的脚本,但是都感觉很不理想,于是,自己造轮子了~ 打印的效果,自己 ...

  9. bootstrap Table 中给某一特定值设置table选中

    bootstrap Table 中给某一特定值设置table选中 需求: 如图所示:左边地图人员选定,右边表格相应选中. 功能代码: //表格和图标联动 function changeTableSel ...

随机推荐

  1. 【LeetCode题解】排序

    1. 排序 排序(sort)是一种常见的算法,把数据根据特定的顺序进行排列.经典的排序算法如下: 冒泡排序(bubble sort) 插入排序(insertion sort) 选择排序(selecti ...

  2. mac上使用使用rz,sz命令

    mac上使用rz,sz命令,mac上的终端不支持rz 和sz,所以安装iterm并配置使用rz和cz 1.首先需要下载安装iterm2,下载地址:下载后安装 http://www.iterm2.cn/ ...

  3. Mybatis(四) 高级映射,一对一,一对多,多对多映射

    天气甚好,怎能不学习? 一.单向和双向 包括一对一,一对多,多对多这三种情况,但是每一种又分为单向和双向,在hibernate中我们就详细解析过这单向和双向是啥意思,在这里,在重复一遍,就拿一对多这种 ...

  4. 腾讯云安全:开发者必看|Android 8.0 新特性及开发指南

    欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 背景介绍 谷歌2017 I/O开发者大会今年将于5月17-19日在美国加州举办.大会将跟往年一样发布最新的 A ...

  5. R语言写2048游戏

    2048 是一款益智游戏,只需要用方向键让两两相同的数字碰撞就会诞生一个翻倍的数字,初始数字由 2 或者 4 构成,直到游戏界面全部被填满,游戏结束. 编程时并未查看原作者代码,不喜勿喷. 程序结构如 ...

  6. redis 字符串

    redis 字符串 概述 redis 没有使用 c 语言风格的字符串表示(以 "\0" 作为结尾), 而是使用自定义的 sds 结构 字符串结构 定义位置 (src/sds.h) ...

  7. .net Framework 4.5 新特性async(异步)的初步认识

    1.async的简单说明 继版本4.5以前,要想实现异步方法,运用多线程齐头并进.而4.5直接一个async修饰的方法配合await实现异步,这里的底层实现原理暂时未研究, 应该本质都一样,对线程的操 ...

  8. Machine Learning——Supervised Learning(机器学习之监督学习)

    监督学习是指:利用一组已知类别的样本调整分类器的参数,使其达到所要求性能的过程. 我们来看一个例子:预测房价(注:本文例子取自业界大牛吴恩达老师的机器学习课程) 如下图所示:横轴表示房子的面积,单位是 ...

  9. 关于v-model、v-for、v-on的用法

    展示Holle Vue     window.onload = function(){         var box = new Vue({             el:'#div',      ...

  10. EmpyoyeeManger_1.0

    整体结构 首先创建一个名为employee的数据库 create database employee; 然后在该数据库下建一张表 CREATE TABLE t_emp( id BIGINT PRIMA ...