在开发过程中,比如配置,服务器下发的数据,这些数据我们不做修改。怎么防止别人的误修改呢。我们可以设置__newindex 元方法来实现:
--把table 变成readobly
---@param t table 对象
function Common.TableReadOnly(t)
if t == nil or type(t) ~= "table" then
return nil
end
local tt = {}
local mt = {
__index = t,
__newindex = function (t,k,v)
error("cant modify read-only table", 2)
end
}
setmetatable(tt,mt)
return tt
end
这样就设值,只要被修改,就会给出错误提示。
只读Lua表
1206

被折叠的 条评论
为什么被折叠?



