dump

function dump( tab [, format] )

Description

The dumps a table. By default will the table be writen to io.stdout, but with the optional format table can the user configure the function.

Parameters

tab

The table to write.

format

A optional table with the optional fields

  • indent with default value 3

  • level with default value 0

  • file with io.stdout as default value

Code

--ZFUNC-dump-v1
local function dump( tab, format )
   format = format or {}
   format.indent = format.indent or 3
   format.level = format.level or 0
   format.file = format.file or io.stdout

   local indent = format.level * format.indent

   for k,v in pairs( tab ) do
      format.file:write( string.rep( " ", indent )..k..":" )

      if type( v ) == "table" then
         format.file:write( "\n" )
         format.level = format.level + 1
         dump( v, format )
         format.level = format.level - 1
      elseif type( v ) == 'boolean' then
         format.file:write( " "..tostring( v ).."\n" )
      else
         format.file:write( " "..v.."\n" )
      end
   end
end

return dump

Examples

local t = require( "tapered" )
local dump = require( "dump" )
-- util functions
local like = require( "like" )
local readlines = require( "readlines" )

tab = { name="james bond", lucky_numbers={ 1, 2, 6, 8 }, cool=true }
f = io.open( "DumpXmpl.txt", "w" )
dump( tab, { file=f } )
f:close()

expect = { "cool: true", "name: james bond", "lucky_numbers:",
           "   1: 1", "   2: 2", "   3: 6", "   4: 8" }
written, err = readlines( "DumpXmpl.txt" )
t.ok( like( expect, written ) )

os.remove( "DumpXmpl.txt" )

t.done()