getmetatable()

The getmetatable() function retrieves the metatable associated with a given table or userdata. Metatables allow you to change the behavior of tables by defining operations like addition, indexing, and method invocation.

Syntax

getmetatable(table)

Parameters

  • Name
    table
    Type
    table|userdata
    Description

    The table or userdata for which you want to retrieve the metatable.

Return

Returns the metatable associated with the specified table or userdata. If the table does not have a metatable, it returns nil.

Description

In Lua, a metatable is a special table that defines how operations on another table behave. The getmetatable() function allows you to access the metatable of a table, which can be useful for debugging or for checking the behavior of tables.

To set a metatable, you can use the setmetatable() function.

Examples

Retrieving a metatable

local myTable = {}
local meta = {
  __index = function(t, k) return "Key not found" end
}

setmetatable(myTable, meta)

local retrievedMeta = getmetatable(myTable)

print(retrievedMeta)  -- Output: table: 0x...

Checking if a table has a metatable

local anotherTable = {}

print(getmetatable(anotherTable))  -- Output: nil (no metatable)

setmetatable(anotherTable, {})

print(getmetatable(anotherTable))  -- Output: table: 0x...

See also

  • setmetatable(): Sets the metatable for a table or userdata.
  • rawget(): Accesses the value of a key in a table without invoking the metatable.

Was this page helpful?

Table of Contents