Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write-once table in lua?

I'd like 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 like a regular table (pairs() and ipairs() work).

__newindex is basically the opposite of what I'd want for implementing this easily, and I am unaware of any techniques for making a proxy table pattern work with pairs() and ipairs().

like image 273
MikeMx7f Avatar asked Nov 03 '17 00:11

MikeMx7f


People also ask

How do you create a table in Lua?

In Lua the table is created by {} as table = {}, which create an empty table or with elements to create non-empty table. After creating a table an element can be add as key-value pair as table1[key]= “value”.

Can you print a table in Lua?

Finally, print() is used for printing the tables. Below are some of the methods in Lua that are used for table manipulation. Strings in the table will be concatenated based on the given parameters. Value val will be inserted into the table at the mentioned position.

What is unpack Lua?

In Lua, if you want to call a variable function f with variable arguments in an array a , you simply write f(unpack(a)) The call to unpack returns all values in a , which become the arguments to f . For instance, if we execute f = string.find a = {"hello", "ll"}

How do you delete a table in Lua?

Question was : “How do you delete a table in Lua ?”. Answer is, plain and simple : assign nil to it. Just : a = nil.


1 Answers

You need to use a proxy table, that is, 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 from Lua 5.2 onwards.

like image 117
lhf Avatar answered Sep 27 '22 21:09

lhf