subdirs

function subdirs( path ) --> iter

Description

Creates a Lua iterator over the sub directories of a given directory, except "." and "..". 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 sub directories in a directory.

Code

local lfs = require( "lfs" )  --ZREQ-lfs
--ZFUNC-subdirs-v1
local function subdirs( path ) --> iter
   --ZFUNC-isdodd-v1
   local function isdodd( e )
      if e == "." or e == ".." then
         return true
      end

      return false
   end

   local function yielddir( path )
      for entry in lfs.dir( path ) do
         local entrypath = path.."/"..entry
         local mode = lfs.attributes( entrypath, "mode" )
         if mode == "directory" and not isdodd( entry ) then
            coroutine.yield( entry )
         end
      end
   end

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

return subdirs

Examples

local t = require( "tapered" )
local subdirs = require( "subdirs" )
-- util functions
local collectk = require( "collectk" )
local mkdirtree = require( "mkdirtree" )
local rmdirtree = require( "rmdirtree" )

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

-- test
dirs = collectk( subdirs( "tmp_subdir" ) )
table.sort( dirs )
t.is( #dirs, 3 )
t.is( "a", dirs[ 1 ] )
t.is( "b", dirs[ 2 ] )
t.is( "c", dirs[ 3 ] )

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

t.done()

See also