gpt4 book ai didi

lua - 如何在lua中实现只读表?

转载 作者:行者123 更新时间:2023-12-03 12:36:10 31 4
gpt4 key购买 nike

我写了一个例子。

 function readOnly(t)  
local newTable = {}
local metaTable = {}
metaTable.__index = t
metaTable.__newindex = function(tbl, key, value) error("Data cannot be changed!") end
setmetatable(newTable, metaTable)
return newTable
end

local tbl = {
sex = {
male = 1,
female = 1,
},
identity = {
police = 1,
student = 2,
doctor = {
physician = 1,
oculist = 2,
}
}
}

local hold = readOnly(tbl)
print(hold.sex)
hold.sex = 2 --error

这意味着我可以访问表“tbl”的字段,但同时我无法更改与该字段相关的值。

现在,问题是我想让所有嵌套表都拥有这个只读
属性。如何改进“只读”方法?

最佳答案

您只需要申请您的 readOnly函数也递归到内部表字段。您可以在 __index 中进行访问元方法。您还应该缓存您创建的只读代理表,否则对内部表的任何读取访问(例如 hold.sex )都将创建一个新的代理表。

-- remember mappings from original table to proxy table
local proxies = setmetatable( {}, { __mode = "k" } )

function readOnly( t )
if type( t ) == "table" then
-- check whether we already have a readonly proxy for this table
local p = proxies[ t ]
if not p then
-- create new proxy table for t
p = setmetatable( {}, {
__index = function( _, k )
-- apply `readonly` recursively to field `t[k]`
return readOnly( t[ k ] )
end,
__newindex = function()
error( "table is readonly", 2 )
end,
} )
proxies[ t ] = p
end
return p
else
-- non-tables are returned as is
return t
end
end

关于lua - 如何在lua中实现只读表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28312409/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com