lua遍历文件

看了不少人的,主要还是错误处理有点问题,不多说了

贴代码:

require "lfs"


function getpathes(rootpath, pathes)
    pathes = pathes or {}

    ret, files, iter = pcall(lfs.dir, rootpath)
    if ret == false then
        return pathes
    end
    for entry in files, iter do
        local next = false
        if entry ~= '.' and entry ~= '..' then
            local path = rootpath .. '/' .. entry
            local attr = lfs.attributes(path)
            if attr == nil then
                next = true
            end

            if next == false then 
                if attr.mode == 'directory' then
                    getpathes(path, pathes)
                else
                    table.insert(pathes, path)
                end
            end
        end
        next = false
    end
    return pathes
end

pathes = {}

getpathes("/", pathes)

for key, path in pairs(pathes) do
    print(key .. " " .. path)
end