User:Merlin11188/Draft: Difference between revisions
>Merlin11188 Added a "do not edit" thing to the page |
>Merlin11188 Added a 'quiz' section. |
||
Line 289: | Line 289: | ||
print(Table[1]) -- will be fast because it's just grabbing the number from the table. | print(Table[1]) -- will be fast because it's just grabbing the number from the table. | ||
</code>}} | </code>}} | ||
==Quiz== | |||
{{User:Merlin11188/Template:Draft| | |||
#Without looking at the list above, which metamethod allows you to add two tables? | |||
#Without looking at the list above, which metamethod allows you to negate a table? | |||
#If run, what will the following code result in?<code lua> | |||
local quizTable = {"Hello", "Hi", "Bonjour"} | |||
setmetatable(quizTable, {__index = function(parent, key) | |||
rawset(parent, key, key * 2 .. tostring(rawget(parent, key/2))) | |||
return key * 2 .. tostring(rawget(parent, key/2)) | |||
end}) | |||
print(quizTable[6]) | |||
</code> | |||
| | |||
#__add. Pretty easy. | |||
#__unm. | |||
#12Bonjour | |||
}} | |||
==See Also== | ==See Also== |
Revision as of 15:22, 14 January 2012
Do not edit! The creator of this subpage does not want it to be edited without permission. |
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.
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]
Metatable Demonstration
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 t[key] 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) at an index that's nil (list.z), the function associated with __index in Metatable is run. The function at __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 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 when 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, Table(arg).
- __concat(Table, Object) — The .. concatenation 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˚
- __mode — Used in Weak Tables, declaring whether the keys and/or values of a table are weak.
- __gc(Object) — Fired when the Object is garbage-collected.
- __len(Object) — Fired when the # operator is used on the Object. NOTE: Only userdatas actually respect the __len() metamethod, this is a bug in Lua 5.1
˚ 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 the __unm metamethod (to make a table negative):
Here's an interesting way to declare things using __index:
__index was fired when x was accessed from the table. __index then defined x as 1 instead of nil; therefore, 1 was returned.
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 table = {10, 20, 30}
print(table(5))
Now, obviously you can't call a table. That's just crazy, but (surprise, surprise!) with metatables you can.
You can do a lot more as well, such as adding tables!
If 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. That
means that you really only have to set the metatable of Table1 or Table2, but it's
nicer and more readable to set the metatable of both.
Here is one last example breaking away from using separate variables when it isn't necessary.
rawset(), rawget(), rawequal()
If you continue to play with metatables, you might encounter problems. Here's a primary example:
Let's say that we want to make a table error() whenever you try to access a nil value in it.
local planets = {Earth = "COOL!"}
local mt = {
__index = function(self, i)
return self[i] or error(i .. " is not a real Planet!") -- If self[i] is nil, then error!
end
}
setmetatable(planets, mt);
print(planets.Earth); --> COOL!
print(planets.Pluto); --> error: C stack overflow
So what does C stack overflow mean? It means you've called the same function too many times inside of itself (or recursed too deeply). You called a function too many times too quickly! The normal limit is actually right around 20,000!
So what caused the __index() method to call itself ? The answer: self[i]
So what can we do? How can we get a member of a table without calling it's __index() method? With rawget(), of course!
Let's make a small change to the code and try again!
local planets = {Earth = "COOL!"}
local mt = {
__index = function(self, i)
return rawget(self, i) or error(i .. " is not a real Planet!")
end
}
setmetatable(planets, mt)
print(planets.Earth) --> COOL!
print(planets.Pluto) --> error: Pluto is not a real Planet!
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:
Quiz
User:Merlin11188/Template:Draft