OOPS! My fault, there’s a typo in the code.
There isn’t really such a thing as immutable data in Lua
TL;DR
To explain more further… One can always play with table’s metamethods to gain poor man’s sort of “immutability” as some sort of “safety net” (if needed)…
function immutable(tbl)
return setmetatable({}, {
__index = tbl,
__newindex = function(tbl, key, val)
error('Cannot modify read-only table')
end,
__metatable = false
})
end
local t = immutable { x = 1, y = 2, z = 3 } -- new "immutable" table `t`
It’s a nice trick but MUST NOT be considered as a “security feature” or something like that because the rawset()
call can still be used to override this!
So, yes, there is simply no real immutability in Lua.