研究网站开发意义,网站建设四个步骤,计算机专业就业方向和前景,wordpress国外付费主题下载参考《programming in lua》13.4.5中#xff0c;详细介绍了只读表的用法。建立一个函数#xff0c;传入一个table#xff0c;传出一个代理table#xff0c;其__index指向传入的table#xff0c;__newIndex直接报error即可#xff1a;
--输入一个table#xff0c;输出一…参考《programming in lua》13.4.5中详细介绍了只读表的用法。建立一个函数传入一个table传出一个代理table其__index指向传入的table__newIndex直接报error即可
--输入一个table输出一个代理table其只读
function table.readOnly(tbTarget)local proxy {}setmetatable(proxy,{__index tbTarget,__newindex function(t,k,v)error(attempt to update a read-only table, 2)end})return proxy
endA {}
A[1] 1B table.readOnly(A)
print(B[1]) --print:1
B[2] 2 --print:attempt to update a read-only table
B[1] a --print:attempt to update a read-only tableA[1] 2
print(B[1]) --print:2
A[2] 3
print(B[2]) --print:3
其中有两个重要的点
1.index重新定位至原table但proxy本身是空表newIndex无论是什么key都会报error不管原table内部是否有这个key。
2.__index实际是地址形式如若中途修改了原table内部的值proxy代理table也会相应改变和定位。