luafilesystem icon indicating copy to clipboard operation
luafilesystem copied to clipboard

Proposal: Add a recursive version of 'dir'

Open Pharap opened this issue 6 years ago • 0 comments

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.

Pharap avatar Dec 20 '19 22:12 Pharap