Page 1 of 1

Metatables

Posted: Sat May 22, 2010 8:32 pm
by Fo-Rum
I have a hard time learning from manuals and your standard tutorials. Can anyone help me understand metatables better?

I read how to attach them and was shown examples of it, but it didn't really click with me. It's just the language used that is the problem for me. Even on things I'm more experienced with I have problems drawing the meaning when reading it in technical format, and shown abstract examples. Abstract + me = bad.

What are the practical uses for a metatable? How might I apply them in a script for a MUD? I'm probably fine without ever using them, but I enjoy using new methods to create things, so I'm really curious about them right now.

Re: Metatables

Posted: Sat May 22, 2010 11:05 pm
by tsuujin
I use metatables to change the way lua stores values in tables, so that I can use a hash style table and still maintain the order I inserted the values in. Basically replicating PHP's tables. The code is freely available, I just modified it a bit.

Honestly, though, metatables are a specialty use thing. You're probably not going to need them in general.

Re: Metatables

Posted: Mon May 24, 2010 9:49 pm
by WillFa
A metatable is a hidden table attached to a table.

It several default keys that have a special behavior:
__index -- is called when the key doesn't exist.
__newidx -- is called when a new value is ADDED (not changed)
__call -- is called when you try to use the table as a function.

are the most common ones.

If you think of a Word document, you have the contents of the file itself -- i.e. your resume, and the properties of it that show up when you click on it in windows explorer -- author, last modified, last printed, word count, etc...
All those properties are free form, you can make up your own and store them.

So, If your table is your resume, the metatable is the property storage.

You can use metatables for variable storage that you want to attach to a table, but not necessarily want to iterate over with pairs(). For example, a table of kills with all the critter names and the number of times you've killed them; you also want to track when you last added a new critter to the table. That time stamp would be out of place in the main table, it'd mess up what you'd expect to loop through with a call to pairs. You could easily make a metatable with a __newidx key that calls a function you write to getmetatable, and then set the timestamp variable in it. This would keep the timestamp current, because incrementing the kill count for a known critter wouldn't call __newidx, but adding a new index would.

Re: Metatables

Posted: Tue May 25, 2010 1:48 pm
by Denarii
It's __newindex

Re: Metatables

Posted: Tue May 25, 2010 6:52 pm
by Fo-Rum
Alright, I think I understand them a bit better at least! It's good to have a start somewhere. Thanks!