Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Protect a value in a table?

Asked by
LuaQuest 450 Moderation Voter
9 years ago

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?

0
I would have thought that the __index metamethod catches changes in the value? Because it will usually cause a c-stack overflow when you try to change it without rawset inside the metamethod. Tkdriverx 514 — 9y

1 answer

Log in to vote
1
Answered by
funyun 958 Moderation Voter
9 years ago
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
0
Why is this downvoted? HungryJaffer 1246 — 9y
1
Not sure, but I'll sure accept this answer. Thanks for the example funyun. LuaQuest 450 — 9y
Ad

Answer this question