How can I dump out a table?

This is one of the things where a nice semi-official library would help. The first question is, do you want to do this for debugging, or wish to write out large tables for later reloading?

A simple solution to the first problem:

function dump(o)
 if type(o) == 'table' then
 local s = '{ '
 for k,v in pairs(o) do
 if type(k) ~= 'number' then k = '"'..k..'"' end
 s = s .. '['..k..'] = ' .. dump(v) .. ','
 end
 return s .. '} '
 else
 return tostring(o)
 end end

However, this is not very efficient for big tables because of all the string concatenations involved, and will freak if you have circular references or 'cycles'.

PiL shows how to handle tables, with and without cycles.

More options are available here.

And if you want to understand a complicated set of related tables, sometimes a diagram is the best way to show relationships; this post gives a script which creates a Graphviz visualisation of table relationships. Here is what a typical result looks like.



Back