如何在Lua 5.4中从当前目录向上查找文件(无luafilesystem)
Lua 5.4 实现从当前目录向上查找项目根目录(以.luacheckrc为标记)
在未安装luafilesystem的Lua 5.4环境中,可通过标准库实现从当前工作目录(或脚本所在目录)逐层向上查找.luacheckrc文件,以此定位项目根目录。以下是完整实现:
local function find_project_root() -- 获取当前执行环境的起始目录 local current_dir local info = debug.getinfo(1, 'S') if info and info.source:sub(1, 1) == '@' then -- 从脚本路径提取目录 local script_path = info.source:sub(2) current_dir = script_path:match('^(.*)[/\\]') or '.' else -- 交互模式下默认使用当前工作目录 current_dir = '.' end -- 逐层向上遍历查找目标文件 local check_dir = current_dir while true do local target_path = check_dir .. '/.luacheckrc' -- 尝试打开文件判断是否存在 local file_handle = io.open(target_path, 'r') if file_handle then file_handle:close() return check_dir end -- 到达文件系统根目录时停止遍历 local parent_dir = check_dir:match('^(.*)[/\\]') if not parent_dir or parent_dir == check_dir then break end check_dir = parent_dir end -- 未找到目标文件时返回nil return nil end -- 调用示例 local project_root = find_project_root() if project_root then print('项目根目录已找到:' .. project_root) else print('未找到.luacheckrc文件,无法确定项目根目录') end
关键说明
- 路径获取逻辑:通过
debug.getinfo获取脚本的执行路径,同时兼容交互模式(此时默认使用当前工作目录) - 文件存在性检查:使用标准库
io.open尝试读取文件,成功打开则说明文件存在(无需额外文件系统库) - 跨路径分隔符兼容:通过匹配
[/\\]同时支持Unix(/)和Windows(\)系统的路径格式 - 终止条件:当遍历到文件系统根目录(父目录与当前目录相同)时停止循环,避免无限遍历
内容的提问来源于stack exchange,提问作者idbrii
相关产品推荐
相关产品推荐

