]> git.e2factory.org Git - e2factory.git/commitdiff
strict: add readonly() function
authorTobias Ulmer <tu@emlix.com>
Thu, 28 Jul 2016 17:44:33 +0000 (19:44 +0200)
committerTobias Ulmer <tu@emlix.com>
Wed, 16 Nov 2016 14:41:18 +0000 (15:41 +0100)
Enforces readonly access on a table. Also errors on accessing nil values

Signed-off-by: Tobias Ulmer <tu@emlix.com>
generic/strict.lua

index 8324d85f5b8e78fd69e9d518385dbf7f5913a4b4..cc51e83a2b05b09652e61d529261f89cb6967459 100644 (file)
@@ -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.