Pretty printing a table

For debugging, I’d like to print the contents of a table. I’m sure that I saw something like this here in one of the discussions, but now I can’t find it. Can anyone point it out? Thanks.

Try to google it. There is a nice hit in the first page to a lua site with a dozen of retty printing functions.

Found this via the wiki: http://www.twolivesleft.com/Codea/Talk/discussion/138/code-for-pretty-printing-a-table-for-example-the-table-containing-all-global-variables

Thanks to both Jmv38 and Andrew_Stacey. Just what I was looking for.

From @pixel via the codea wiki. Pass it a table and if any special way to indent it.

http://twolivesleft.com/Codea/Talk/discussion/138/code-for-pretty-printing-a-table-for-example-the-table-containing-all-global-variables#Item_4

function dump(t,indent)
    local names = {}
    if not indent then indent = "" end
    for n,g in pairs(t) do
        table.insert(names,n)
    end
    table.sort(names)
    for i,n in pairs(names) do
        local v = t[n]
        if type(v) == "table" then
            if(v==t) then -- prevent endless loop if table contains reference to itself
                print(indent..tostring(n)..": <-")
            else
                print(indent..tostring(n)..":")
                dump(v,indent.."   ")
            end
        else
            if type(v) == "function" then
                print(indent..tostring(n).."()")
            else
                print(indent..tostring(n)..": "..tostring(v))
            end
        end
    end
end

I ran pixel code on my ipad1 and it consistantly freezes codea. Didnt happen to you?

No issues here, I use it often for debugging but I’m running an iPad2

I ran it on _G as in his setup. Did you try that?

Yeah… dump(_G) kills codea :slight_smile:

It’s likely that _G has circular references and the code above only checks for those that refer to the same table that is being dumped.

I’ve written a serializer/pretty printer that deals with circular/shared references and can pretty print a table in line or block format: http://notebook.kulchenko.com/programming/serpent-lua-serializer-pretty-printer

Other options listed here: http://lua-users.org/wiki/TableSerialization