setrawmetatable
Sets the metatable of an object, bypassing __metatable guards.
function setrawmetatable(object: any, newMt: table?): anySynopsis
How it works
A raw metatableMetatableA table attached to another table (or userdata) that defines operator overloading via metamethods (__index, __newindex, __call, etc.). Roblox Instances use shared read-only metatables for method dispatch. setter that bypasses any
__metatable metamethodMetamethodA function in a metatable that overrides default behavior for operations like indexing (__index), assignment (__newindex), calling (__call), comparison (__eq), and arithmetic (__add, __mul, etc.).. Luau's standard setmetatable() checks for a __metatable field and throws "cannot change protected metatable" if present. setrawmetatable() directly writes the metatable pointer on the object's header, ignoring that protection.Use case
Roblox locks InstanceInstanceThe base class for all Roblox objects (Parts, Models, Scripts, GUIs, etc.). Instances form a tree hierarchy (the DataModel). In Luau, they appear as userdata with shared metatables. metatablesMetatableA table attached to another table (or userdata) that defines operator overloading via metamethods (__index, __newindex, __call, etc.). Roblox Instances use shared read-only metatables for method dispatch. with
__metatable. To hook __index or __namecall you need getrawmetatable to read it, modify the fields, and optionally use setrawmetatable to swap it entirely. Works on any Luau value that supports metatables — tables and userdataUserdataA Luau type for C-allocated memory blocks. Roblox Instances, Vector3s, CFrames, and other engine types are userdata with metatables providing their API. Cannot be created from Luau directly..Usage
Override a locked metatable
local mt = getrawmetatable(game)
setreadonly(mt, false)
mt.__index = function(self, key)
print("Index:", key)
return rawget(mt, key)
end
setreadonly(mt, true)Parameters
object any The object whose metatable to replace.
newMt table? The new metatable, or nil to remove it.
Returns
any The original object (for chaining).
Stability
Replacing Roblox object metatables can crash the client. Always restore the original when done.