Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Human readable string representation of table in Lua

Tags:

lua

I am new to Lua and want to print the contents of a table for debugging purposes. I can do that by iterating over the table myself. However, since this strikes me as a very common problem, I expect there must be an out of the box way of doing that or someone must have written a nice library that does that. WHat's the standard way of doing this in Lua?

like image 905
ajmurmann Avatar asked Feb 08 '12 16:02

ajmurmann


People also ask

Can you print a table in Lua?

Finally, print() is used for printing the tables. Below are some of the methods in Lua that are used for table manipulation. Strings in the table will be concatenated based on the given parameters.

How do you create a Lua table?

In Lua the table is created by {} as table = {}, which create an empty table or with elements to create non-empty table. After creating a table an element can be add as key-value pair as table1[key]= “value”.

How do I convert a character to a string in Lua?

The character representation of a decimal or integer value is nothing but the character value, which one can interpret using the ASCII table. In Lua, to convert a decimal value to its internal character value we make use of the string. char() function.


2 Answers

For better or worse, there's no standard. Lua is known for what it excludes as much as for what it includes. It doesn't make assumptions about proper string representations because there's no one true way to handle things like formats, nested tables, function representation, or table cycles. That being said, it doesn't hurt to start with a "batteries-included" Lua library. Maybe consider Penlight. Its pl.pretty.write does the trick.

like image 188
Corbin March Avatar answered Oct 17 '22 05:10

Corbin March


This is an instance of the general problem of table serialization.

Take a look at the Table Serialization page at lua-users for some serious implementations.

My throw at it is usually quickly defining a function like

function lt(t) for k,v in pairs(t) do print(k,v) end end
like image 25
jpjacobs Avatar answered Oct 17 '22 06:10

jpjacobs