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( "tapered" )
local dirfiles = require( "dirfiles" )
-- util functions
local collectk = require( "collectk" )
local mkdirtree = require( "mkdirtree" )
local rmdirtree = require( "rmdirtree" )

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

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

-- teardown
t.ok( rmdirtree( "tmp_dirfiles" ) )

t.done()

See also