setmetatable()
The setmetatable()
function is used to set or change the metatable for a given table in Lua. Metatables are tables that define how operations on another table behave. By setting a metatable, you can customize table behavior for operations like addition, indexing, and method calls.
Syntax
setmetatable(table, metatable)
Parameters
- Name
table
- Type
- table
- Description
The table for which the metatable will be set.
- Name
metatable
- Type
- table
- Description
The new metatable to be associated with the specified table.
Return
Returns the table that was passed as the first parameter.
Description
Using setmetatable()
, you can define custom behaviors for table operations by utilizing fields in the metatable such as __index
, __newindex
, and others. This allows for powerful object-oriented programming techniques in Lua.
Examples
Setting a simple metatable
local myTable = {}
local myMetatable = {
__index = function(t, key)
return "Key " .. key .. " not found!"
end
}
setmetatable(myTable, myMetatable)
print(myTable.someKey) -- Output: Key someKey not found!
Customizing table addition
local vector1 = { x = 1, y = 2 }
local vector2 = { x = 3, y = 4 }
setmetatable(vector1, {
__add = function(v1, v2)
return { x = v1.x + v2.x, y = v1.y + v2.y }
end
})
local result = vector1 + vector2
print(result.x, result.y) -- Output: 4 6
See also
getmetatable()
: Retrieves the metatable for a given table.rawset()
: Sets a value in a table without invoking the metatable's__newindex
.rawget()
: Retrieves a value from a table without invoking the metatable's__index
.