monome / norns

norns is many sound instruments.
http://monome.org
GNU General Public License v3.0
614 stars 144 forks source link

add a util function for making readonly table proxies #663

Closed pq closed 5 years ago

pq commented 5 years ago

follow-up from the discussion in https://github.com/monome/norns/pull/657#issuecomment-443471472, a function that creates immutable tables would be really handy.

something like this, minimally, may work:

function readonly (t)
    local proxy = {}
    local mt = {
      __index = t, 
      __newindex = function (t,k,v)
        error("attempt to update a read-only table", 2)
      end,
      __pairs = function (t) return pairs(proxy) end,
      __ipairs = function (t) return ipairs(proxy) end,
    }
    setmetatable(proxy, mt)
    return proxy
end
pq commented 5 years ago

thinking about our concrete use cases we probably want to allow for the specification of writable exceptions -- e.g., engine.name.

maybe something like:

local proxiedEngine = readonly{table: engine, exceptFor: {'name'}}