How to traverse a folder in Lua to get file names?

In Lua, you can use the lfs (Lua File System) library to iterate through folders and retrieve file names. Here is an example:

lfs = require("lfs")

function traverseFolder(path)
    for file in lfs.dir(path) do
        if file ~= "." and file ~= ".." then
            local filePath = path .. "/" .. file
            local attr = lfs.attributes(filePath)
            if attr.mode == "directory" then
                traverseFolder(filePath) -- 递归遍历子文件夹
            else
                print(file) -- 打印文件名
            end
        end
    end
end

traverseFolder("path/to/folder")

In this example, the traverseFolder function takes a folder path as a parameter and uses lfs.dir to traverse the files and subfolders in the folder. For each file, if it is a folder, the traverseFolder function is recursively called; otherwise, the file name is printed.

bannerAds