Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Protect a value in a table?

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?

1 comment

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.

1 answer

✓ Accepted answer
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

2 comments

0

Why is this downvoted?

1

Not sure, but I'll sure accept this answer. Thanks for the example funyun.

This discussion is preserved as it was. New answers, comments, and votes are closed.