Lua - 如何按照字母顺序排序所有发现的文件(通过LFS)?

请问是否有人能帮我完成通过Lua文件系统提取的所有文件名排序函数呢?因为我似乎做不到。以下是代码。(感谢所有提供帮助的人)


local lfs = require "lfs"
local json = require("json")
local tt = {}

function browseFolder(root)
    for entity in lfs.dir(root) do
        if entity~="." and entity~=".." then

            local fullPath=root..'/'..entity
            local mode=lfs.attributes(fullPath,"mode")
            if mode=="file" and entity: match "%.mkv$" then

                table.insert(tt, {
                    filename = entity,
                    folder = root})

            elseif mode=="directory" then

                browseFolder(fullPath);
            end
        end
    end
end

browseFolder(".")

--print(tt)

table.sort(tt, function(a, b) return a:filename() < b:filename() end)

for k,d in ipairs(tt) do
    --print(d.filename)
    print(k, d.filename, d.folder)
--end
end

并且... 如果有人知道另外一个也包括文件大小,创建日期等其他文件属性的函数,并能够通过任何一个来排序,那将是非常好的。

点赞
用户7504558
用户7504558

使用 lfs.attributes 和完整路径来访问文件:

local lfs = require "lfs"
local json = require("json")
local tt = {}

function browseFolder(root)
    for entity in lfs.dir(root) do
        if entity~="." and entity~=".." then

            local fullPath=root..'/'..entity
            local mode=lfs.attributes(fullPath,"mode")
            if mode=="file" and entity: match "%.*$" then -- 所有文件

                table.insert(tt, {
                    filename = entity,
                    folder = root,
                    date_ch = lfs.attributes(root .. '//'.. entity, "change")
                    })
                print(entity,root)
            elseif mode=="directory" then

                browseFolder(fullPath);
            end
        end
    end
end

browseFolder(".")

table.sort(tt, function(a, b) return a.date_ch < b.date_ch end) -- 按修改日期排序

for k,d in pairs(tt) do
    print(k, d.filename, os.date("%c",d.date_ch) , d.folder)
end

而不是使用 a:filename() < b:filename(),要使用 a.filename < b.filename

2020-12-21 12:15:38