How to dump a table to console?

If the requirement is “quick and dirty”

I’ve found this one useful. Because of the recursion it can print nested tables too. It doesn’t give the prettiest formatting in the output but for such a simple function it’s hard to beat for debugging.

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

e.g.

local people = {
   {
      name = "Fred",
      address = "16 Long Street",
      phone = "123456"
   },

   {
      name = "Wilma",
      address = "16 Long Street",
      phone = "123456"
   },

   {
      name = "Barney",
      address = "17 Long Street",
      phone = "123457"
   }

}

print("People:", dump(people))

Produces the following output:

People: { [1] = { [“address”] = 16 Long Street,[“phone”] =
123456,[“name”] = Fred,} ,[2] = { [“address”] = 16 Long
Street,[“phone”] = 123456,[“name”] = Wilma,} ,[3] = { [“address”] = 17
Long Street,[“phone”] = 123457,[“name”] = Barney,} ,}

Leave a Comment