Write-once table in lua?

I want to have a write once table in Lua (specifically LuaJIT 2.0.3) so that:

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

Ideally, this would otherwise function as a regular table (pairs () and ipairs () work).

__ newindex is basically the opposite of what I would like to implement for this, and I don’t know about any methods for creating a proxy server template work with pairs () and ipairs ().

+4
source share
1 answer

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 __pairsand __ipairsonly work with Lua 5.2.

+5
source

Source: https://habr.com/ru/post/1688648/


All Articles