I've seen the rawset
function used in Metatables but how does it really work?
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