How to dump a table to console?

lua
Cliff picture Cliff · Feb 6, 2012 · Viewed 167.9k times · Source

I'm having trouble displaying the contents of a table which contains nested tables (n-deep). I'd like to just dump it to std out or the console via a print statement or something quick and dirty but I can't figure out how. I'm looking for the rough equivalent that I'd get when printing an NSDictionary using gdb.

Answer

kikito picture kikito · Feb 7, 2012

I know this question has already been marked as answered, but let me plug my own library here. It's called inspect.lua, and you can find it here:

https://github.com/kikito/inspect.lua

It's just a single file that you can require from any other file. It returns a function that transforms any Lua value into a human-readable string:

local inspect = require('inspect')

print(inspect({1,2,3})) -- {1, 2, 3}
print(inspect({a=1,b=2})
-- {
--   a = 1
--   b = 2
-- }

It indents subtables properly, and handles "recursive tables" (tables that contain references to themselves) correctly, so it doesn't get into infinite loops. It sorts values in a sensible way. It also prints metatable information.

Regards!