setmetatable()

Type Function
Library (globals)
Return value Table
Revision Current Public Release (2017.3068)
Keywords table, metatable
See also getmetatable()

Overview

Sets the metatable for the given table (you cannot change the metatable of other types from Lua, only from C). If metatable is nil, removes the metatable of the given table. If the original metatable has a __metatable field, it raises an error.

This function returns the same table that was provided as the first argument of the function, now with its metatable set.

Syntax

setmetatable( table, metatable )
table (required)

Table. The Lua table whose metatable you want to modify.

metatable (required)

Table. The Lua table to set as the new metatable for table.

Example

local t = {}
local mt = { __index = t }

function t.new()
    return setmetatable( {}, mt )
end

return t