Write a table in Lua?

I want to use a write-once table in Lua (especially LuaJIT 2.0.3), like this:

local tbl = write_once_tbl()
tbl["a"] ='foo'
tbl["b"] ='bar'
tbl["a"] ='baz' - asserts false

Ideally, this will behave like a regular table (pairs() and ipairs() work).

__newindex is basically the opposite of how I want to achieve it, I don’t know any technology that uses pair() and ipairs() to make proxy table mode work.

You need to use a proxy table, an empty table that captures all access rights 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

Please note that __ pairs and __ipairs Only applicable to Lua 5.2 and higher.

I want to use a write-once table in Lua (especially LuaJIT 2.0.3), like this:

local tbl = write_once_tbl( )
tbl["a"] ='foo'
tbl["b"] ='bar'
tbl["a"] ='baz' - asserts false

Ideally, this will run like regular tables (pairs() and ipairs() work).

__newindex is basically the opposite of how I want to achieve it, I don’t know any Use pair() and ipairs() to make the proxy table mode work.

You need to use a proxy table, that is, one that captures all access rights to the actual table Empty 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< br /> error("table is write-once")
end
end,
__pairs = function (t) return pairs(T) end,
__ipairs = function (t ) return ipairs(T) end,
})
end

Please note that __ pairs and __ipairs are only applicable to Lua 5.2 and later.

Leave a Comment

Your email address will not be published.