Metatables

Metatables allow tables to become more powerful than before. They are attached to data and contain values called metamethods. Metamethods are fired when a certain action is used with the datum that it is attached to.

You may think that if you have code like this:


1local list = {1, 2}
2print(list[3])
3

The code will search through the list for the third index in list, realize it's not there, and return nil. That's totally wrong. What really happens is the code will search through the list for the third index, realize it's not there, and then try to see if there's a metatable attached to the table, returning nil if there isn't one.

Manipulating Metatables

The two primary functions for giving and finding a table's metatable, are setmetatable and getmetatable


1local x = {}
2local metaTable = {} -- metaTables are tables, too!
3setmetatable(x, metaTable) -- Give x a metatable called metaTable!
4print(getmetatable(x)) --> table: [hexadecimal memory address]
5

The setmetatable function also returns the table that you're setting the metatable of, so these two scripts do the same thing:


1local x = {}
2setmetatable(x, {})
3

1local x = setmetatable({}, {})
2

Metamethods

Metamethods are the functions that are stored inside a metatable. They can go from calling a table, to adding a table, to even dividing tables as well. Here's a list of metamethods that can be used:

Method Description
__index(table, index) Fires when table[index] is indexed, if table[index] is nil. Can also be set to a table, in which case that table will be indexed.
__newindex(table, index, value) Fires when table[index] tries to be set (table[index] = value), if table[index] is nil. Can also be set to a table, in which case that table will be indexed.
__call(table, ...) Fires when the table is called like a function, ... is the arguments that were passed.
__concat(table, value) Fires when the .. concatenation operator is used on the table.
__unm(table) Fires when the unary – operator is used on the table.
__add(table, value) The + addition operator.
__sub(table, value) The – subtraction operator.
__mul(table, value) The * mulitplication operator.
__div(table, value) The / division operator.
__mod(table, value) The % modulus operator.
__pow(table, value) The ^ exponentiation operator.
__tostring(table) Fired when tostring is called on the table.
__metatable If present, locks the metatable so getmetatable will return this instead of the metatable and setmetatable will error. Non-function value.
__eq(table, value) The == equal to operator¹
__lt(table, value) The < less than operator¹; Note: Using the <= greater than or equal to operator will invoke this metamethod and return the opposite of what this returns, as greater than or equal to is the same as not less than.
__le(table, value) The <= operator¹; Note: Using the < greater than operator will invoke this metamethod and return the opposite of what this returns, as greater than is the same as not less than or equal to.
__mode Used in weak tables, declaring whether the keys and/or values of a table are weak. Note: References to Roblox instances are never weak. Tables that hold such references will never be garbage collected.
__gc(table) Fired when the table is garbage-collected. Note: On Roblox, this metamethod is disabled.
__len(table) Fired when the # length operator is used on the Object. Note: Only userdatas actually respect the __len() metamethod in Lua 5.1.

It should be noted that when writing functions for either arithmetic or relational metamethods the two function parameters are interchangeable between the table that fired the metamethod and the other value. For example, when doing vector operations with scalars division is not commutative. Therefore if you were writing metamethods for your own vector2 class, you'd want to be careful to account for either scenario.


1local vector2 = {__type = "vector2"}
2local mt = {__index = vector2}
3
4function mt.__div(a, b)
5 if (type(a) == "number") then
6 -- a is a scalar, b is a vector
7 local scalar, vector = a, b
8 return vector2.new(scalar / vector.x, scalar / vector.y)
9 elseif (type(b) == "number") then
10 -- a is a vector, b is a scalar
11 local vector, scalar = a, b
12 return vector2.new(vector.x / scalar, vector.y / scalar)
13 elseif (a.__type and a.__type == "vector2" and b.__type and b.__type == "vector2") then
14 -- both a and b are vectors
15 return vector2.new(a.x / b.x, a.y / b.y)
16 end
17end
18
19function mt.__tostring(t)
20 return t.x .. ", " .. t.y;
21end;
22
23function vector2.new(x, y)
24 local self = setmetatable({}, mt)
25 self.x = x or 0
26 self.y = y or 0
27 return self
28end
29
30local a = vector2.new(10, 5)
31local b = vector2.new(-3, 4)
32
33print(a / b) -- -3.3333333333333, 1.25
34print(b / a) -- -0.3, 0.8
35print(2 / a) -- 0.2, 0.4
36print(a / 2) -- 5, 2.5
37

Using Metatables

There are many ways to use metatables, for example the __unm metamethod (to make a table negative):


1local metatable = {
2 __unm = function(t) -- __unm is for the unary - operator
3 local negated = {}
4 for key, value in pairs(t) do
5 negated[key] = -value -- negate all of the values in this table
6 end
7 return negated -- return the table
8 end
9}
10
11local table1 = setmetatable({10, 11, 12}, metatable)
12print(table.concat(-table1, "; ")) --> -10; -11; -12
13

Here's an interesting way to declare things using __index:


1local metatable = {
2 __index = {x = 1}
3}
4
5local t = setmetatable({}, metatable)
6print(t.x) --> 1
7

__index was fired when x was indexed in the table and not found. Lua then searched through the __index table for an index called x, and, finding one, returned that.

Now you can easily do that with a simple function, but there's a lot more where that came from. Take this for example:


1local t = {10, 20, 30}
2print(t(5))
3

Now, obviously you can't call a table. That's just crazy, but (surprise, surprise!) with metatables you can.


1local metatable = {
2 __call = function(t, param)
3 local sum = {}
4 for i, value in ipairs(t) do
5 sum[i] = value + param -- Add the argument (5) to the value, then place it in the new table (t).
6 end
7 return unpack(sum) -- Return the individual table values
8 end
9}
10
11local t = setmetatable({10, 20, 30}, metatable)
12print(t(5)) --> 15 25 35
13

You can do a lot more as well, such as adding tables!


1local table1 = {10, 11, 12}
2local table2 = {13, 14, 15}
3
4for k, v in pairs(table1 + table2) do
5 print(k, v)
6end
7

This will error saying that you're attempting to perform arithmetic on a table. Let's try this with a metatable.


1local metatable = {
2 __add = function(t1, t2)
3 local sum = {}
4 for key, value in pairs(t1) do
5 sum[key] = value
6 end
7
8 for key, value in pairs(t2) do
9 if sum[key] then
10 sum[key] = sum[key] + value
11 else
12 sum[key] = value
13 end
14 end
15 return sum
16 end
17}
18
19local table1 = setmetatable({10, 11, 12}, metatable)
20local table2 = setmetatable({13, 14, 15}, metatable)
21
22for k, v in pairs(table1 + table2) do
23 print(k, v)
24end
25

Use Cases

Now, all of these examples can be implemented as a simple function, but you can do a lot more than that. Let's try a simple program that will memorize a number when a possibly laggy math problem is put into it.

For this one we will be using the __index metamethod just to make it simple:


1local function mathProblem(num)
2 for i = 1, 20 do
3 num = math.floor(num * 10 + 65)
4 end
5 for i = 1, 10 do
6 num = num + i - 1
7 end
8 return num
9end
10
11local metatable = {
12 __index = function (object, key)
13 local num = mathProblem(key)
14 object[key] = num
15 return num
16 end
17}
18
19local t = setmetatable({}, metatable)
20
21print(t[1]) -- Will be slow because it's the first time using this number, so it has to run the math function.
22print(t[2]) -- will be slow because it's the first time using this number.
23print(t[1]) -- will be fast because it's just grabbing the number from the table.
24

Rawset, Rawget, Rawequal

When playing with metatables, you may run into some problems. What happens if you need to use the __index metamethod to create new values in a table, but that table's metatable also has a __newindex metamethod in it? You'll want to use the Lua built-in function rawset to set the value without invoking any metamethods. Take the following code as an example of what happens if you don't use these functions.


1local t = setmetatable({}, {
2 __index = function(self, i)
3 self[i] = i * 10 -- just as an example
4 return self[i]
5 end,
6 __newindex = function(self, i, v)
7 --don't do anything because we don't want you to set values to the table the normal way
8 end
9})
10print(t[1]) -- Causes a C-Stack overflow
11

Now why would that cause a stack overflow? Stack overflows happen when you try to call a function from itself too many times, but what would cause that to happen? In the __index function, we set self[i] to a value, so when it gets to the next line, self[i] should exist, so it won't call the __index metamethod, right?

The problem is that __newindex doesn't let us set the value. Its presence stops values from being added to the table with the standard t[i] = v method. In order to get past this, you use the rawset function.


1local t = setmetatable({}, {
2 __index = function(self, i)
3 rawset(self, i, i * 10)
4 return self[i]
5 end,
6 __newindex = function(self, i, v)
7 --don't do anything because we don't want you to set values to the table the normal way
8 end
9})
10print(t[1]) -- prints 10
11

Using the Set Datatype

A set is a collection of items with no order and no duplicate elements. An item either is or is not contained within a set. Using metatables, you can construct and manipulate sets within Lua scripts.

Basic Methods

The following code includes basic set functionality, letting you construct new sets, add and remove an item, check if a set contains an item, and output the contents of a set.


1local Set = {}
2Set.__index = Set
3
4-- Function to construct a set from an optional list of items
5function Set.new(items)
6 local newSet = {}
7 for key, value in ipairs(items or {}) do
8 newSet[value] = true
9 end
10 return setmetatable(newSet, Set)
11end
12
13-- Function to add an item to a set
14function Set:add(item)
15 self[item] = true
16end
17
18-- Function to remove an item from a set
19function Set:remove(item)
20 self[item] = nil
21end
22
23-- Function to check if a set contains an item
24function Set:contains(item)
25 return self[item] == true
26end
27
28-- Function to output set as a comma-delimited list for debugging
29function Set:output()
30 local elems = {}
31 for key, value in pairs(self) do
32 table.insert(elems, tostring(key))
33 end
34 print(table.concat(elems, ", "))
35end
36

Create Set

A new set can be constructed by calling Set.new() with an optional array of items to add.


1local fruits = Set.new({"Apple", "Lemon", "Orange", "Cherry", "Lime", "Peach"})
2

Note that by definition, a set has no concept of ordering.

Add Item

Adding an item to an existing set can be done via the Set:add() method.


1local fruits = Set.new({"Apple", "Lemon", "Orange", "Cherry", "Lime", "Peach"})
2fruits:add("Mango")
3

Remove Item

To remove an item from a set, call Set:remove() with the item name.


1local fruits = Set.new({"Apple", "Lemon", "Orange", "Cherry", "Lime", "Peach"})
2fruits:remove("Orange")
3

Check for Item

To check if a set contains a specific item, use Set:contains().


1local fruits = Set.new({"Apple", "Lemon", "Orange", "Cherry", "Lime", "Peach"})
2
3local result1 = fruits:contains("Cherry")
4print(result1) -- true
5
6local result2 = fruits:contains("Watermelon")
7print(result2) -- false
8

Additional Methods

Other useful operations can be implemented for sets, letting you compare items between sets, combine sets, or subtract one set from another.

Intersection

When considering sets as venn diagrams, you can get the intersection of two sets as follows, meaning the items that appear in both sets.


1local function getIntersection(set1, set2)
2 local result = Set.new()
3 for key, value in pairs(set1) do
4 if set2:contains(key) then
5 result:add(key)
6 end
7 end
8 return result
9end
10
11local freshFruits = Set.new({"Mango", "Lemon", "Orange", "Cherry", "Lime", "Peach"})
12local frozenFruits = Set.new({"Mango", "Peach", "Pineapple"})
13
14local commonFruits = getIntersection(freshFruits, frozenFruits)
15commonFruits:output() -- Mango, Peach
16

Union

You can get the union of two sets with the following function, meaning a collection of the items in both sets with no duplicates. Note that this function uses the metatable __add method to provide an addition shortcut of set1 + set2.


1function Set:__add(otherSet)
2 local result = Set.new()
3 for entry in pairs(self) do
4 result[entry] = true
5 end
6 for entry in pairs(otherSet) do
7 result[entry] = true
8 end
9 return result
10end
11
12local sweetFruits = Set.new({"Apple", "Mango", "Cherry", "Peach"})
13local sourFruits = Set.new({"Lemon", "Lime"})
14
15local allFruits = sweetFruits + sourFruits
16allFruits:output() -- Peach, Lime, Apple, Cherry, Lemon, Mango
17
18

Subtraction

You can remove all items in one set from the items in another set via the following function. Similar to the function above, this uses the metatable __sub method to provide a subtraction shortcut of set1 - set2.


1function Set:__sub(otherSet)
2 local result = Set.new()
3 for entry in pairs(self) do
4 result[entry] = true
5 end
6 for entry in pairs(otherSet) do
7 result[entry] = nil
8 end
9 return result
10end
11
12local allFruits = Set.new({"Apple", "Lemon", "Mango", "Cherry", "Lime", "Peach"})
13local sourFruits = Set.new({"Lemon", "Lime"})
14
15local sweetFruits = allFruits - sourFruits
16sweetFruits:output() -- Mango, Apple, Cherry, Peach
17