From: Tobias Ulmer Date: Thu, 28 Jul 2016 17:44:33 +0000 (+0200) Subject: strict: add readonly() function X-Git-Tag: e2factory-2.3.15rc1~130 X-Git-Url: https://git.e2factory.org/?a=commitdiff_plain;h=40624378514fadaa1d7c3a2cdabbc351b6868204;p=e2factory.git strict: add readonly() function Enforces readonly access on a table. Also errors on accessing nil values Signed-off-by: Tobias Ulmer --- diff --git a/generic/strict.lua b/generic/strict.lua index 8324d85..cc51e83 100644 --- a/generic/strict.lua +++ b/generic/strict.lua @@ -74,6 +74,34 @@ function strict.lock(t) return t end +function strict.readonly(t) + assertIsTable(t) + local mt = {} + + if getmetatable(t) ~= nil then + error("metatable already set") + end + + mt.__declared = {} -- for .islocked() compat + + mt.__newindex = function(t, k, v) + error(err.new("attempted assignment to read-only (%s) [%s] = %s", + tostring(t), tostring(k), tostring(v))) + end + + mt.__index = function(t, k) + local v = rawget(t, k) + if v == nil then + error(err.new("attempted read of nil value in (%s) [%s]", + tostring(t), tostring(k))) + end + return v + end + + setmetatable(t, mt) + return t +end + --- Unlock a table that was protected against adding and assigning to fields. -- @param t table to unlock. -- @return the unlocked table.