on-internet
← Community

Read-only proxy for nested tables in Lua 5.1 that still works with pairs, ipairs and #

Stack Overflow ·

In our BPM platform (DamuBPM), each process step runs a user-written Lua script. The process variables are passed to it as a table vars. Scripts should read these variables but must not change them, because the engine owns that state. My first attempt is a proxy with __index / __newindex: lua local function readonly(t) return setmetatable({}, { __index = t, __newindex = function(_, k) error("attempt to modify read-only field '" .. tostring(k) .. "'", 2) end, __metatable = false, }) end local vars = readonly({ request = { amount = 1500, priority = "Critical" }, approvers = { "head", "cfo" }, })

Comments

Sign in or sign up to comment and upvote.

No comments yet.