lunarmodules / luafilesystem

LuaFileSystem is a Lua library developed to complement the set of functions related to file systems offered by the standard Lua distribution.
https://lunarmodules.github.io/luafilesystem/
MIT License
907 stars 293 forks source link

Proposal: Add a recursive version of 'dir' #133

Open Pharap opened 4 years ago

Pharap commented 4 years ago

While it's completely possible to implement this in plain Lua, it's a fair bit of effort on the user's part. Having this functionality as part of the library would be quite useful.

A Lua implementation might look something like this:

local function recursedir(top)
    local dir = lfs.dir
    local insert = table.insert
    local remove = table.remove

    local directories = {}
    local directory = top
    local iterator, directoryObject = dir(directory)

    return function()
        local filename = iterator(directoryObject)

        while filename == nil do
            if #directories == 0 then
                return nil
            end

            directory = remove(directories)
            iterator, directoryObject = dir(directory)
            filename = iterator(directoryObject)
        end

        local path = directory..pathSeparator..filename

        if filename ~= '..' and filename ~= '.' then
            local attributes = getAttributes(path)                  
            if attributes ~= nil and attributes.mode == 'directory' then
                insert(directories, path)
            end
        end

        return path
    end
end

I expect a C implementation could be made more efficient.