Help with metatables

It’s really your call whether to go through __tostring or just write individual routines as the need arises. I think a motivation for both it and print () was to complement stuff like the command line interpreter (available with the Lua source code, but usually not bundled with stuff like Corona) or the live demo, which obviously aren’t going to know about your routines. But it’s only a library metamethod; nothing in the language proper would break if you removed  tostring () and print ().

If you had objects of several different types in an array or whatever, rather than figuring out what each one is and calling its special logic, you can just call print () on each one blindly and let it do its thing.

(In 5.2 and on, pairs() itself honors a library metamethod. But Corona uses 5.1, so this is merely a curiosity.)

A plain old loop and printing each element can fall short, at times. If the table isn’t shallow, for instance, which is to say some or all of its elements are themselves tables, with their own elements. You can recurse or use a stack to handle this, but then you need to account for cycles. At this point, you’re also likely to notice some structure to your data, so you might start to indent it and try to draw pretty ASCII art.  :D Also, if you have large data sets, your printouts might end up flooding the console (which will probably confuse rather than help), and so you’ll start adding features to stagger, abridge, or reroute the output. And so on. These kind of things call for a lot of work, which you won’t want to throw away.

Once that stuff is available, it might be convenient to wire it into some of your objects from the outset, and  __tostring is right there

@ tilen.curin: yes, you would be using the __index key, naturally. I used “shorthand” in my example because it is only about the principles, not the syntax.

Regarding your “Every example I’ve seen has been something useless and every time there was a way around.” I do believe that there is no other way to do OOP-like instancing that is this powerful or flexible without using metatables.

I’ll try to connect everything I’ve read so far and try out a few things.

Really want to get comfortable using metatables. Guess I’ll have to learn through experience.

I pretty much get how they work, but I’ll need to actually start working with them.