Metatables

setrawmetatable

Sets the metatable for a target value and returns the original target.

Syntax

setrawmetatable(target: any, metatable: table | nil): any
Aliases debug.setmetatable

Arguments

NameTypeDescription
targetanyValue whose metatable is changed.
metatabletable | nilNew metatable, or nil to clear the metatable. Other types raise "nil or table".

Returns

NameTypeDescription
targetanyThe original target value.

Description

Sets the metatable for a target value and returns the original target. metatable must be a table or nil; nil clears the metatable. debug.setmethods is an alias for setrawmethods.

Call it with 2 parameter(s): target, metatable. The argument table explains which values are required and which ones only refine the behavior.

It returns target (any). Use the returns table to separate successful values from nil results and recoverable errors.

Example

Set or clear a value's metatable and receive the target back.

local target = {}
local meta = { label = "Real" }

local returned = setrawmetatable(target, meta)
print(returned == target)
print(getrawmetatable(target) == meta)

debug.setmetatable(target, nil)
print(getrawmetatable(target))