User:Merlin11188/Draft: Difference between revisions
>Merlin11188 No edit summary |
>Merlin11188 |
||
Line 23: | Line 23: | ||
Output: | Output: | ||
attempt to concatenate field 'z' (a nil value) | <font color="red">attempt to concatenate field 'z' (a nil value)</font color> | ||
</pre> | </pre> | ||
z is nil. Now, look at what happens with metatables: | z is nil. Now, look at what happens with metatables: |
Revision as of 18:30, 8 July 2011
Metatables
What is a Metatable?
Metatables allow tables to become more powerful than before. 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 and see if there's a metatable attached to the list and then return nil if there isn't one.
Demonstration
local List={1,2} print("In table List, index z is "..List.z) Output: <font color="red">attempt to concatenate field 'z' (a nil value)</font color>
z is nil. Now, look at what happens with metatables:
local List={1,2} local Metatable={ __index=function(Table, Index) rawset(Table, Index, 0) -- Set Table[Index] to 0 return Table[Index] -- return Table[Index] (which is now 0) end } setmetatable(List, Metatable) print("In table List, index z is "..List.z) Output: In table List, index z is 0
What happened there? List is a normal table, with nothing unusual about it. Metatable is
also a table, but it has something special: the __index metamethod. The __index metamethod
is fired when Table[Index] is nil; or, in this case, List.z is nil. Now, nothing would happen
because the two tables (List and Metatable) aren't linked. That's what the third line does:
sets List's metatable to Metatable, which means that when List is indexed (__index) in an
index that's nil (List.z), the function associated with __index in Metatable is run. The
function with __index in Metatable uses rawset to make a new value in the Table (or List).
Then, that value is returned. So, List.z is set equal to 0, and then List.z is returned
(which is 0).
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:
- __index(Table, Index) — Fires when Table[Index] is nil
- __newindex(Table, Index, Value) — Fires at Table[Index] = Value when Table[Index] is nil
- __call(Table, arg) — Allows the table to be used as a function, arg is the arguments passed
- __concat(Table, Object) — The .. concatination operator.
- __unm(Table) — The unary – operator.
- __add(Table, Object) — The + addition operator.
- __sub(Table, Object) — The – subtraction operator.
- __mul(Table, Object) — The * mulitplication operator.
- __div(Table, Object) — The / division operator.
- __mod(Table, Object) — The % modulus operator.
- __pow(Table, Object) — 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, Table2) — The == equal to operator˚
- __lt(Table, Table2) — The < less than operator˚
- __le(Table, Table2) — The <= operator˚
- __gc(Object) - Fired when the Object is garbage-collected
- __len(Object) - Fired when the # operator is used on the Object.
˚ Requires two tables; does not work with a table and a number, string, etc. The tables must have the same metatable.
Using Metatables
There are many ways to use metatables, for example, if you were to type in:
local Table = { x = 1, y = 2, } print(Table.z) Output: nil
This would be obvious because z isn't even defined in the table. However, we can
make this work with metatables. Here's how to do it:
local Table = { x = 1, y = 2, } local Metatable = { __index = function (table, key) print(table, key) return 0 end } setmetatable(Table, Metatable) print(Table.z) Output: table: 0037AAF8 z
Now you can easily do that with a simple function, but there's a lot more where
that came from. Take this for example:
Table = {10,20,30} print(Table(5))
Now, obviously you can't call a table. That's just crazy, but with metatables you can.
local Table = {10,20,30} local Metatable = { __call = function (table, arg) local t = {} for i, v in ipairs(table) do t[i] = v + arg end return unpack(t) end } setmetatable(Table, Metatable) print(Table(5)) Output: 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.
local Table1 = {10,11,12} local Table2 = {13,14,15} local Metatable = { __add = function (table1, table2) local t = {} local index = 0 for i, v in ipairs(table1) do index = index + 1 t[index] = v end for i, v in ipairs(table2) do index = index + 1 t[index] = v end return t end } setmetatable(Table1, Metatable) setmetatable(Table2, Metatable) for k, v in pairs(Table1 + Table2) do print(k, v) end Output: 1 10 2 11 3 12 4 13 5 14 6 17
If a the two tables have two different __add functions, then Lua will go to table1
first and if it doesn't have an __add function, then it'll go to the second one.
Here is one last example breaking away from using separate variables when it isn't necessary.
local t = setmetatable({10, 20, 30}, {__call = function(a, b) return table.concat(a, b..' ')..b end}) print('Tables contains '..t(1)) --> Tables contains 101 201 301
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 Table = {} 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 setmetatable(Table, Metatable) print(Table[1]) -- Will be slow because it's the first time using this number. print(Table[2]) -- will be slow because it's the first time using this number. print(Table[1]) -- will be fast because it's just grabbing the number from the table.