遍历 Lua Torch 中的目录

Iterating over directories in Lua Torch

在 Torch 中,我正在遍历一个充满子文件夹的文件夹,如下所示:

subfolders = {}
counter = 0

for d in paths.iterdirs(root-directory) do
      counter = counter + 1
      subfolders[counter] = d
      -- do something with the subfolders' contents
end

当我打印子文件夹时,子文件夹似乎是以随机顺序访问的。相反,想要按名称顺序迭代它们。我该怎么做呢?谢谢!

使用以下方法解决:

subfolders = {}
counter = 0

local dirs = paths.dir(root-directory)
table.sort(dirs)

for i = 1, 447 do
    counter = counter + 1
    subfolders[counter] = dirs[i]
end

我需要一个比 Chris 的答案更可靠的解决方案,它不排除普通文件、父目录 (..) 或当前目录 (.)。我也不确定他代码中的神奇数字 447 是什么。 Standard Lua doesn't have a way to check if a file is a directory,所以这只适用于 Linux/OSX。

function isSubdir(path)
    noError, result = pcall(isDir, path)
    if noError then return result else return false end
end

-- Credit: 
function isDir(path)
    local f = io.open(path, 'r')
    local ok, err, code = f:read(1)
    f:close()
    return code == 21
end

function getSubdirs(rootDir)
    subdirs = {}
    counter = 0
    local dirs = paths.dir(rootDir)
    table.sort(dirs)
    for i = 1, #dirs do
        local dir = dirs[i]
        if dir ~= nil and dir ~= '.' and dir ~= '..' then
            local path = rootDir .. '/' .. dir
            if isSubdir(path) then
                counter = counter + 1
                subdirs[counter] = path
            end
        end
    end
    return subdirs
end

local subdirs = getSubdirs('/your/root/path/here')
print(subdirs)