Menu
Coddy logo textTech

setmetatable & getmetatable

Part of the Logic & Flow section of Coddy's Lua journey — lesson 17 of 54.

Now that you understand what metatables are conceptually, it's time to learn how to actually work with them. Lua provides two essential functions for this: setmetatable() to attach a metatable to a table, and getmetatable() to retrieve it.

To attach a metatable to a table, you use setmetatable(). This function takes two arguments: the table you want to modify (the main table) and the metatable you want to attach to it:

local myTable = {name = "Alice"}
local myMetatable = {}

setmetatable(myTable, myMetatable)

In this example, myMetatable is now attached to myTable. The metatable itself is empty for now, but this establishes the connection between the two tables. The setmetatable() function also returns the main table, which allows you to chain the operation if needed.

To retrieve the metatable attached to a table, you use getmetatable():

local retrievedMeta = getmetatable(myTable)
print(retrievedMeta == myMetatable)  -- Output: true

This function returns the metatable if one is attached, or nil if the table has no metatable. This is useful when you need to check or modify a table's metatable after it has been set.

Understanding these two functions is the foundation for all metatable work in Lua. Once you can attach and retrieve metatables, you'll be ready to define metamethods that change how your tables behave.

challenge icon

Challenge

Easy

Write a function attachMetatable that takes mainTable and metaTable and returns true if the metatable was successfully attached.

Use setmetatable() to attach the metatable to the main table, then verify the attachment using getmetatable().

Logic:

  • Attach metaTable to mainTable using setmetatable()
  • Retrieve the attached metatable using getmetatable()
  • Compare the retrieved metatable with the original metaTable
  • Return true if they match, false otherwise

Parameters:

  • mainTable (table): The table to which the metatable will be attached
  • metaTable (table): The metatable to attach

Returns: true if the metatable was successfully attached and verified, false otherwise (boolean)

Cheat sheet

Lua provides two essential functions for working with metatables:

setmetatable() - Attaches a metatable to a table. Takes two arguments: the main table and the metatable to attach. Returns the main table.

local myTable = {name = "Alice"}
local myMetatable = {}

setmetatable(myTable, myMetatable)

getmetatable() - Retrieves the metatable attached to a table. Returns the metatable if one is attached, or nil if the table has no metatable.

local retrievedMeta = getmetatable(myTable)
print(retrievedMeta == myMetatable)  -- Output: true

Try it yourself

function attachMetatable(mainTable, metaTable)
    -- Write code here
end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow