【发布时间】:2018-06-06 00:27:53
【问题描述】:
我想在我的 Lua 程序中有一个只读表。如果删除了某个键或将某个键与新值关联,则必须抛出错误。
function readonly(table)
local meta = { } -- metatable for proxy
local proxy = { } -- this table is always empty
meta.__index = table -- refer to table for lookups
meta.__newindex = function(t, key, value)
error("You cannot make any changes to this table!")
end
setmetatable(proxy, meta)
return proxy -- user will use proxy instead
end
效果很好。
t = { }
t["Apple"] = "Red"
t[true] = "True!"
t[51] = 29
for k,v in pairs(t) do
print(v)
end
t = readonly(t)
t[51] = 30
打印
Red
True!
29
input:7: You cannot make any changes to this table!
问题
for k, v in pairs(t) do
print(v)
end
现在在任何情况下都不会打印任何内容。那是因为proxy 表里面永远不会有任何东西。 pairs 显然从不调用 index,因此无法从实际表中检索任何内容。
如何使这个只读表可迭代?
我在 Lua 5.1 上并且可以访问这些元方法:
【问题讨论】: