In Lua, you will commonly need to store items or references in a table, and sometimes it’s necessary to know which items/members exist inside that table. This is simple enough to do with a key-value loop using the Lua pairs() function:

This will print something like the following to the Terminal/console:

Note that the order may differ, since the pairs() function does not necessarily iterate through the table in the same order in which the key-values were declared. However, if you only need to check for a key’s existence and its value, this loop method is perfectly acceptable.

What About Sub-Tables?

What if your table has a sub-tables as in the following example?

In this case, the above loop method will print something like this:

As you can see, the loop will display the internal references to those tables, but it won’t display the actual content of the sub-tables.

Fortunately, we can use a function from the Corona Community Code Exchange that will intelligently step through tables and sub-tables, revealing the contents for your reference. This function, named print_r, is named after the similar function used in PHP to dump tables to the console. This function has become a staple in my personal utility library and I use it frequently to check what’s inside a table returned by an event or network request.

Here is the print_r function in its entirety:

This function will navigate through the table/sub-tables and print the contents. When running it on the example table above, the output becomes:

Alternative Reference

Since this function is for printing of table contents, it may not be intuitive to use it directly as in:

Thus, an alternative is to add the print_r function to the Lua table object as so:

Then, calling it via the reference becomes more sensible:

Conclusion

Using tables to store items and references is focal to any serious development in Lua and Corona, and knowing the content of those tables is often essential to debugging. Hopefully this function will help you throughout the course of your app development!

This article:  

Tutorial: Printing Table Contents