You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lua中列出目录(文件夹)内容?

在Lua中遍历目录内容的方法

Lua标准库没有内置目录遍历的API,下面提供两种满足需求的实现方式:

一、不依赖外部库(利用系统命令)

通过调用操作系统的终端命令来获取目录内容,无需额外安装库,需根据系统适配命令。

跨平台实现示例

local function list_dir(path)
    -- 判断操作系统类型
    local is_windows = package.config:sub(1, 1) == "\\"
    -- 清理路径末尾的分隔符
    path = path:gsub(is_windows and "\\$" or "/$", "")
    
    -- 构造对应系统的命令
    local cmd
    if is_windows then
        -- Windows下用dir命令,/b显示简洁格式,/a包含所有条目
        cmd = 'dir "' .. path .. '" /b /a'
    else
        -- Linux/macOS下用ls命令,-1每行显示一个条目
        cmd = 'ls -1 "' .. path .. '"'
    end
    
    -- 执行命令并读取输出
    local handle = io.popen(cmd)
    if not handle then return nil, "无法访问目标目录" end
    
    local entries = {}
    local sep = is_windows and "\\" or "/"
    for entry in handle:lines() do
        table.insert(entries, path .. sep .. entry)
    end
    
    handle:close()
    return entries
end

-- 测试调用
local target_dir = "/home/user" -- Windows下可改为类似"C:\\Users\\YourName"
local items, err = list_dir(target_dir)
if items then
    for _, item in ipairs(items) do
        print(item)
    end
else
    print("错误:", err)
end

注意事项

  • 路径包含空格或特殊字符时,用双引号包裹路径避免命令执行出错
  • 依赖系统命令的输出格式,若系统命令行为变更可能影响结果

二、使用轻量外部库LuaFileSystem(LFS)

如果可以接受安装轻量库,LuaFileSystem是跨平台的文件系统操作库,功能更可靠。

示例代码

-- 先确保已安装LuaFileSystem,可通过luarocks install luafilesystem安装
local lfs = require 'lfs'

local function list_dir(path)
    local entries = {}
    -- 遍历目录条目
    for entry in lfs.dir(path) do
        -- 跳过当前目录(.)和上级目录(..)
        if entry ~= "." and entry ~= ".." then
            local full_path = path .. "/" .. entry
            table.insert(entries, full_path)
        end
    end
    return entries
end

-- 拓展:区分文件和目录
local function list_dir_with_type(path)
    local entries = {}
    for entry in lfs.dir(path) do
        if entry ~= "." and entry ~= ".." then
            local full_path = path .. "/" .. entry
            local attr = lfs.attributes(full_path)
            table.insert(entries, {
                path = full_path,
                type = attr.mode -- 取值为file、directory等
            })
        end
    end
    return entries
end

-- 测试调用
local target_dir = "/home/user"
local items = list_dir(target_dir)
for _, item in ipairs(items) do
    print(item)
end

内容的提问来源于stack exchange,提问作者VasiliNovikov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:12:47