From 40624378514fadaa1d7c3a2cdabbc351b6868204 Mon Sep 17 00:00:00 2001 From: Tobias Ulmer Date: Thu, 28 Jul 2016 19:44:33 +0200 Subject: [PATCH] strict: add readonly() function Enforces readonly access on a table. Also errors on accessing nil values Signed-off-by: Tobias Ulmer --- generic/strict.lua | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) 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. -- 2.39.5