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

How does rawset technically work?

Asked by
woodengop 1134 Moderation Voter
9 years ago

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

1 answer

Log in to vote
1
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

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
0
Thanks! woodengop 1134 — 9y
Ad

Answer this question