Metatables: Difference between revisions
m Text replacement - "</code>" to "</SyntaxHighlight>" |
m Text replacement - "<code lua>" to "<SyntaxHighlight code="lua">" |
||
Line 5: | Line 5: | ||
You may think that if you have code like this: | You may think that if you have code like this: | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local list = {1, 2} | local list = {1, 2} | ||
print(list[3]) | print(list[3]) | ||
Line 21: | Line 21: | ||
The two primary functions for giving and finding a table's metatable, are [[setmetatable]] and [[getmetatable]]. | The two primary functions for giving and finding a table's metatable, are [[setmetatable]] and [[getmetatable]]. | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local x = {} | local x = {} | ||
local metaTable = {} -- metaTables are tables, too! | local metaTable = {} -- metaTables are tables, too! | ||
Line 30: | Line 30: | ||
The setmetatable function also returns the table that you're setting the metatable of, so these two scripts do the same thing: | The setmetatable function also returns the table that you're setting the metatable of, so these two scripts do the same thing: | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local x = {} | local x = {} | ||
setmetatable(x, {}) | setmetatable(x, {}) | ||
</SyntaxHighlight> | </SyntaxHighlight> | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local x = setmetatable({}, {}) | local x = setmetatable({}, {}) | ||
</SyntaxHighlight> | </SyntaxHighlight> | ||
Line 110: | Line 110: | ||
There are many ways to use metatables, for example the __unm metamethod (to make a table negative): | There are many ways to use metatables, for example the __unm metamethod (to make a table negative): | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local metatable = { | local metatable = { | ||
Line 127: | Line 127: | ||
Here's an interesting way to declare things using __index: | Here's an interesting way to declare things using __index: | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local metatable = { | local metatable = { | ||
__index = {x = 1} | __index = {x = 1} | ||
Line 140: | Line 140: | ||
Now you can easily do that with a simple function, but there's a lot more where | Now you can easily do that with a simple function, but there's a lot more where | ||
that came from. Take this for example: | that came from. Take this for example: | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local t = {10, 20, 30} | local t = {10, 20, 30} | ||
print(t(5)) | print(t(5)) | ||
Line 148: | Line 148: | ||
with metatables you can. | with metatables you can. | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local metatable = { | local metatable = { | ||
__call = function(t, param) | __call = function(t, param) | ||
Line 164: | Line 164: | ||
You can do a lot more as well, such as adding tables! | You can do a lot more as well, such as adding tables! | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local table1 = {10, 11, 12} | local table1 = {10, 11, 12} | ||
local table2 = {13, 14, 15} | local table2 = {13, 14, 15} | ||
Line 213: | Line 213: | ||
For this one we will be using the __index metamethod just to make it simple: | For this one we will be using the __index metamethod just to make it simple: | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local function mathProblem(num) | local function mathProblem(num) | ||
for i = 1, 20 do | for i = 1, 20 do | ||
Line 243: | Line 243: | ||
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 [[Function_Dump/Core_Functions#rawset_.28table.2C_index.2C_value.29|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. | 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 [[Function_Dump/Core_Functions#rawset_.28table.2C_index.2C_value.29|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. | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local t = setmetatable({}, { | local t = setmetatable({}, { | ||
__index = function(self, i) | __index = function(self, i) | ||
Line 260: | Line 260: | ||
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. | 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. | ||
<code lua> | <SyntaxHighlight code="lua"> | ||
local t = setmetatable({}, { | local t = setmetatable({}, { | ||
__index = function(self, i) | __index = function(self, i) |
Revision as of 04:11, 27 April 2023
What is a Metatable?
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:
local list = {1, 2}
print(list[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
setmetatable() and getmetatable()
The two primary functions for giving and finding a table's metatable, are setmetatable and getmetatable.
local x = {}
local metaTable = {} -- metaTables are tables, too!
setmetatable(x, metaTable) -- Give x a metatable called metaTable!
print(getmetatable(x)) --> table: [hexadecimal memory address]
The setmetatable function also returns the table that you're setting the metatable of, so these two scripts do the same thing:
local x = {}
setmetatable(x, {})
local x = setmetatable({}, {})
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. |
__gc(table) | Fired when the table is garbage-collected. |
__len(table) | Fired when the # length operator is used on the Object. NOTE: Only userdatas actually respect the __len() metamethod in Lua 5.1 |
˚ Requires two values with the same metatable; does not work with a table and another random value.
Using Metatables
There are many ways to use metatables, for example the __unm metamethod (to make a table negative):
local metatable = {
__unm = function(t) -- __unm is for the unary - operator
local negated = {}
for key, value in pairs(t) do
negated[key] = -value -- negate all of the values in this table
end
return negated -- return the table
end
}
local table1 = setmetatable({10, 11, 12}, metatable)
print(table.concat(-table1, "; ")) --> -10; -11; -12
Here's an interesting way to declare things using __index:
local metatable = {
__index = {x = 1}
}
local t = setmetatable({}, metatable)
print(t.x) --> 1
__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:
local t = {10, 20, 30}
print(t(5))
Now, obviously you can't call a table. That's just crazy, but (surprise, surprise!) with metatables you can.
local metatable = {
__call = function(t, param)
local sum = {}
for i, value in ipairs(t) do
sum[i] = value + param -- Add the argument (5) to the value, then place it in the new table (t).
end
return unpack(sum) -- Return the individual table values
end
}
local t = setmetatable({10, 20, 30}, metatable)
print(t(5)) --> 15 25 35
You can do a lot more as well, such as adding tables!
local table1 = {10, 11, 12}
local table2 = {13, 14, 15}
for k, v in pairs(table1 + table2) do
print(k, v)
end
This will error saying that you're attempting to perform arithmetic on a table. Let's try this with a metatable.
Use Cases
Now, I am well aware that you can do all of these as a simple function yourself, but there's a lot more than what you think it can do. 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:
local function mathProblem(num)
for i = 1, 20 do
num = math.floor(num * 10 + 65)
end
for i = 1, 10 do
num = num + i - 1
end
return num
end
local metatable = {
__index = function (object, key)
local num = mathProblem(key)
object[key] = num
return num
end
}
local t = setmetatable({}, metatable)
print(t[1]) -- Will be slow because it's the first time using this number, so it has to run the math function.
print(t[2]) -- will be slow because it's the first time using this number.
print(t[1]) -- will be fast because it's just grabbing the number from the table.
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.
local t = setmetatable({}, {
__index = function(self, i)
self[i] = i * 10 -- just as an example
return self[i]
end,
__newindex = function(self, i, v)
--don't do anything because we don't want you to set values to the table the normal way
end
})
print(t[1]) -- Causes a C-Stack overflow
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.
local t = setmetatable({}, {
__index = function(self, i)
rawset(self, i, i * 10)
return self[i]
end,
__newindex = function(self, i, v)
--don't do anything because we don't want you to set values to the table the normal way
end
})
print(t[1]) -- prints 10