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

How does rawset technically work?

I've seen the rawset function used in Metatables but how does it really work?

1 answer

✓ Accepted answer

When dealing with metatables, simply setting a Table value:

local t = {}

t[1] = true

Can invoke the __newindex metamethod (if the Value was nil before.)

The problem with this is that __newindex trying to set the Table will recursively invoke the __newindex function!

local t = setmetatable({}, {
	__newindex = function(self, i, v)
		print("Trying to set value " .. v .. " at index " .. i .. " of the following Table:")
		print(self)

		self[i] = v
	end
})

t[2] = true --This causes a maximum recursion depth error.

rawset is used to bypass this 'flaw' of __newindex by directly setting the memory of the Table, without invoking any metamethods at all:

local t = setmetatable({}, {
	__newindex = function(self, i, v)
		print("Trying to set value " .. v .. " at index " .. i .. " of the following Table:")
		print(self)

		rawset(self, i, v)
	end
})

t[2] = true

1 comment

0

Thanks!

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