lua只读表

参考《programming in lua》13.4.5中,详细介绍了只读表的用法。建立一个函数,传入一个table,传出一个代理table,其__index指向传入的table,__newIndex直接报error即可:

Lua 复制代码
--输入一个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
end

A = {}
A[1] = 1

B = 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 table

A[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也会相应改变和定位。

相关推荐
diegoXie4 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条4 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
liulilittle4 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
失散134 小时前
Python——1 概述
开发语言·python
萧鼎4 小时前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法
小小8程序员5 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++
立志成为大牛的小牛5 小时前
数据结构——五十六、排序的基本概念(王道408)
开发语言·数据结构·程序人生·算法
老王熬夜敲代码5 小时前
C++中的atomic
开发语言·c++·笔记·面试
a努力。5 小时前
腾讯Java面试被问:String、StringBuffer、StringBuilder区别
java·开发语言·后端·面试·职场和发展·架构
长安第一美人6 小时前
php出现zend_mm_heap corrupted 或者Segment fault
开发语言·嵌入式硬件·php·zmq·工业应用开发