setrawmetatable

Sets the raw metatable of an object.

Syntax

setrawmetatable<T>(object: T, metatable: table?) -> T

Also available as debug.setmetatable.

Parameters

ParameterTypeDescription
objectanyThe object to modify
metatabletable?The new metatable, or nil to remove it

Returns

TypeDescription
TThe original object

Description

setrawmetatable sets the metatable of an object directly, bypassing normal restrictions.

Example

local myTable = {}

-- Create a custom metatable
local mt = {
    __index = function(self, key)
        return "Key not found: " .. key
    end
}

local result = setrawmetatable(myTable, mt)

print(myTable.anything) -- "Key not found: anything"
print(result == myTable) -- true

Replacing Metatables

local object = {}
local originalMt = getrawmetatable(object)

-- Set a new metatable
setrawmetatable(object, {
    __tostring = function()
        return "Custom string!"
    end
})

print(tostring(object)) -- "Custom string!"

-- Restore the original metatable (including nil)
setrawmetatable(object, originalMt)

Caution

Modifying metatables of game objects can cause unexpected behavior or crashes. Always keep a reference to the original.