You need to use a proxy table, i.e. an empty table that catches all access to the actual table:
function write_once_tbl()
local T={}
return setmetatable({},{
__index=T,
__newindex=
function (t,k,v)
if T[k]==nil then
T[k]=v
else
error("table is write-once")
end
end,
__pairs= function (t) return pairs(T) end,
__ipairs= function (t) return ipairs(T) end,
})
end
Note that __pairs
and __ipairs
only work with Lua 5.2.
source
share