setrawmetatable
Sets the raw metatable of an object.
Syntax
setrawmetatable<T>(object: T, metatable: table?) -> TAlso available as debug.setmetatable.
Parameters
| Parameter | Type | Description |
|---|---|---|
object | any | The object to modify |
metatable | table? | The new metatable, or nil to remove it |
Returns
| Type | Description |
|---|---|
T | The 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) -- trueReplacing 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.
Related Functions
getrawmetatable- Get a raw metatable