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( "taptest" )
local collectk = require( "collectk" )
local mkdirtree = require( "mkdirtree" )
local rmdirtree = require( "rmdirtree" )
local subdirs = require( "subdirs" )

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

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

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

t()

See also