示例工程 15-index-and-newindex
15-index-and-newindex/01-readonly-table/main.lua
-- @runtimes lua54 luajit
--- 演示:__newindex 阻止写入。
local M = {}
local function readonly(data)
return setmetatable({}, {
__index = data,
__newindex = function()
error("attempt to update a read-only table", 2)
end,
})
end
--- @return table { value = integer, blocked = boolean }
function M.run(log)
log = log or print
local config = readonly({ port = 8080 })
local blocked = not pcall(function()
config.port = 9090
end)
log(("value=%d blocked=%s"):format(config.port, tostring(blocked)))
return { value = config.port, blocked = blocked }
end
if not ... then
M.run()
end
return M