filelist

function filelist( tree [, root] ) --> list

Description

Converts a tree structure that represents directories with files into a list of files.

Parameters

tree

Lua table where two types of key/value pairs are expected.

  • string/table = the string is the name of a dictionary(table)

  • index/string = the string value is a filename, the index is not relevant

root

Optional root directory that will be used as parent directory for all entries in the tree.

Return Values

list

List of file paths

Code

--ZFUNC-filelist-v1
local function filelist( tree, root )
   local list = {}

   for name, v in pairs( tree ) do
      if type( v ) == "table" then
         local path = root and root.."/"..name or name
         local sublist = filelist( v, path )
         for _, file in ipairs( sublist ) do
            table.insert( list, file )
         end
      elseif type( v ) == "string" and v ~= "" then
         local file = root and root.."/"..v or v
         table.insert( list, file )
      end
   end

   return list;
end

return filelist

Examples

local t = require( "taptest" )
local filelist = require( "filelist" )

list = filelist{
   "aaa",
   [ "abc" ] = {
      "file1.txt",
      "file2.txt",
      [ "max" ] = {
         "min"
      },
      [ "x/yz" ] = { -- it is allowd to merge paths in directory names
         "beg.itr",
         "end.itr"
      },
      "zztop"
   },
   [ "empty" ] = { -- empty directory will be ignored
   },
   [ "foo" ] = {
      "bar",
      "" -- empty strings will will be ignored
   },
   "zztop"
}
table.sort( list )
t( #list, 9 )
t( list[ 1 ], "aaa" )
t( list[ 2 ], "abc/file1.txt" )
t( list[ 3 ], "abc/file2.txt" )
t( list[ 4 ], "abc/max/min" )
t( list[ 5 ], "abc/x/yz/beg.itr" )
t( list[ 6 ], "abc/x/yz/end.itr" )
t( list[ 7 ], "abc/zztop" )
t( list[ 8 ], "foo/bar" )
t( list[ 9 ], "zztop" )

tree = {
   [ "a" ] = { "1", "2", "3" },
   [ "xx" ] = { "a", "b" }
}
list = filelist( tree, "Z" ) -- use "Z" as root
table.sort( list )
t( #list, 5 )
t( list[ 1 ], "Z/a/1" )
t( list[ 2 ], "Z/a/2" )
t( list[ 3 ], "Z/a/3" )
t( list[ 4 ], "Z/xx/a" )
t( list[ 5 ], "Z/xx/b" )

t()