I'm trying to figure out how to "lock" a value in a table. Basically like:
local t = { x = 1; } -- So if someone tried to change "x", it would be set back to default t.x = 2
So, if someone tried to change a key (or the key's value) in a table, that already exists, how would i go about doing that? The __index and __newindex metamethods only work when the key doesn't exist, so is there any way i could make the script catch changes to existing data in a table?
unprotected = { a = 1, b = 2, c = 3 } protected = { d = 4, e = 5, f = 6 } --Anything that's already in the table will be unprotected. t = setmetatable(unprotected, { __metatable = "The metatable is locked", --Lock it up __index = protected, --If it's not in the table, it's a key protected by __newindex. __newindex = function(self, key, value) if protected[key] then error("Key '"..key.."' is protected in this table.") else rawset(self, key, value) end end }) t.a = 5 print(t.a) t.d = 5 print(t.d) --You might find this useful in a module or in _G. You might not. --return t --_G.t = t