Lesson 5: Tables and Metatables in Lua

April 24, 2024

Tables are one of the fundamental data structures in Lua, offering a versatile way to store and organize data. In this lesson, we will explore the power of tables in Lua and delve into the concept of metatables, which allow for custom behavior to be associated with tables.

Tables in Lua

In Lua, tables are used to store collections of data. They can hold a mix of different data types, including numbers, strings, functions, and even other tables. Tables in Lua are versatile and can be used to represent arrays, lists, dictionaries, and more.

To create a table in Lua, you can use curly braces {} and specify key-value pairs:

local myTable = { key1 = 'value1', key2 = 'value2' }

You can access elements in a table using square brackets []:

print(myTable['key1']) -- Output: value1

Metatables in Lua

Metatables in Lua provide a way to define custom behavior for tables. By setting a metatable for a table, you can define operations such as addition, subtraction, comparison, and more.

To set a metatable for a table, you can use the setmetatable function:

local myTable = { key = 'value' }
local metaTable = { __index = { key = 'default' } }
setmetatable(myTable, metaTable)
print(myTable['key']) -- Output: value
print(myTable['nonExistentKey']) -- Output: default

In the above example, the metatable defines a default value for keys that do not exist in the table.

Metatables can also define custom behavior for various operators. For example, you can define a custom addition operation for tables:

local table1 = { value = 10 }
local table2 = { value = 20 }
local metaTable = { __add = function (t1, t2) return { value = t1.value + t2.value } end }
setmetatable(table1, metaTable)
setmetatable(table2, metaTable)
local result = table1 + table2
print(result.value) -- Output: 30

Metatables open up a world of possibilities for customizing the behavior of tables in Lua, making them a powerful tool for creating complex data structures and implementing advanced functionality.