Menu
Coddy logo textTech

What is a Metatable?

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

A metatable is simply a regular Lua table, but it has a special purpose. When you attach a metatable to another table (let's call it the "main" table), you can change how that main table behaves when certain operations are performed on it.

Think of it like this: normally, if you try to add two tables together using the + operator, Lua doesn't know what to do and will give you an error. But with a metatable, you can define what addition means for your tables. You could make it add corresponding values, concatenate their contents, or do anything else that makes sense for your program.

Metatables work by defining special functions called metamethods. These metamethods have specific names that start with two underscores, like __add for addition or __index for looking up missing keys. When Lua encounters an operation on a table that has a metatable, it checks if the metatable has the corresponding metamethod and uses it to determine what should happen.

This concept opens up possibilities like creating custom data types with their own behaviors, implementing object-oriented patterns, protecting tables from unwanted modifications, and much more. In the upcoming lessons, you'll learn how to attach metatables to tables and use metamethods to customize their behavior.

Cheat sheet

A metatable is a regular Lua table that can be attached to another table to change its behavior for certain operations.

Metatables use special functions called metamethods with names starting with two underscores:

  • __add - defines addition behavior
  • __index - defines behavior for looking up missing keys

When an operation is performed on a table with a metatable, Lua checks for the corresponding metamethod and uses it to determine the behavior.

Metatables enable:

  • Creating custom data types with specific behaviors
  • Implementing object-oriented patterns
  • Protecting tables from unwanted modifications

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

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

All lessons in Logic & Flow