dirfiles

function dirfiles( path ) --> iter

Description

Creates a Lua iterator over files of a given directory. Raises an error if path is not a directory.

Parameters

path

A path to a directory in the filesystem.

Return Values

iter

Lua iterator for the files in a directory.

Code

local lfs = require( "lfs" ) --ZREQ-lfs

--ZFUNC-dirfiles-v1
local function dirfiles( path ) --> iter
   local function yielddir( path )
      for entry in lfs.dir( path ) do
         local entrypath = path.."/"..entry
         local mode = lfs.attributes( entrypath, "mode" )
         if mode == "file" then
            coroutine.yield( entry )
         end
      end
   end

   return coroutine.wrap( function() yielddir( path ) end )
end

return dirfiles

Examples

local t = require( "taptest" )
local collectk = require( "collectk" )
local dirfiles = require( "dirfiles" )
local mkdirtree = require( "mkdirtree" )
local rmdirtree = require( "rmdirtree" )

-- setup
t( mkdirtree{
   [ "tmp_dirfiles" ] = {
      [ "a" ] = {},
      [ "x" ] = "",
      [ "b" ] = {},
      [ "y" ] = "",
      [ "c" ] = {},
      [ "z" ] = ""
   }
}, true )

-- test
files = collectk( dirfiles( "tmp_dirfiles" ) )
table.sort( files )
t( #files, 3 )
t( files[ 1 ], "x" )
t( files[ 2 ], "y" )
t( files[ 3 ], "z" )

-- teardown
t( rmdirtree( "tmp_dirfiles" ), true )

t()

See also