Metatables: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>JulienDethurens
>JulienDethurens
Line 44: Line 44:
</code>
</code>


So what does <tt>C stack overflow</tt> mean?
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!
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 <tt>__index()</tt> method to call itself ?
So what caused the __index() method to call itself?
The answer: <tt>self[i]</tt>
The answer: self[i].


So what can we do? How can we get a member of a table without calling it's <tt>__index()</tt> method?
So what can we do? How can we get a member of a table without calling it's __index() metamethod?
With [[Function_Dump/Core_Functions#rawget_.28table.2C_index.29|rawget()]], of course!  
With [[Function_Dump/Core_Functions#rawget_.28table.2C_index.29|rawget()]], of course!




Line 70: Line 70:
print(planets.Pluto)    --> error: Pluto is not a real Planet!
print(planets.Pluto)    --> error: Pluto is not a real Planet!
</code>
</code>


==Metatable Demonstration==
==Metatable Demonstration==

Revision as of 04:41, 30 January 2012

The metatables for Strings and all ROBLOX types are locked; however, in normal Lua (not RBX.lua) you can set the metatables of these objects using the debug library.[1]

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]

rawset(), rawget(), rawequal()

setmetatable() is good for creating a proper metatable, but you might encounter problems.

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!") 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() metamethod? With rawget(), of course!


rawget(), rawset(), and rawequal() are very important when making custom metatables because they do not invoke a table's metamethods, so things like __index and __newindex aren't activated!


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!

Metatable Demonstration

Example
{{{1}}}


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 an index that doesn't have a value yet is indexed.
  • __newindex(table, index, value) — Fires when a new value is inserted to the table.
  • __call(table, ...) — Allows the table to be used as a function, ... is the arguments that were passed.
  • __concat(table, value) — The .. concatenation operator.
  • __unm(table) — The unary – operator.
  • __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() — 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˚
  • __le(table, value) — The <= operator˚
  • __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 # operator is used on the Object. NOTE: Only userdatas actually respect the __len() metamethod

˚ 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):

Example
{{{1}}}


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

Example
{{{1}}}


__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.

Example
{{{1}}}


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

Example
{{{1}}}


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.

Example
{{{1}}}


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:

Example
{{{1}}}


See Also