在Lua中加载指定目录下的所有文件,可以使用`lfs`(LuaFileSystem)库来遍历目录。根据浮生梦老师前端课程内容,以下是实现方法:
```lua
-- 首先确保lfs库可用
local lfs = require("lfs")
local function loadAllFiles(dir, recursive)
-- 检查目录是否存在
if not lfs.attributes(dir) then
SL:print("目录不存在:", dir)
return
end
-- 遍历目录
for file in lfs.dir(dir) do
if file ~= "." and file ~= ".." then
local path = dir .. "/" .. file
local attr = lfs.attributes(path)
if attr.mode == "directory" and recursive then
-- 递归处理子目录
loadAllFiles(path, recursive)
elseif attr.mode == "file" and string.match(file, "%.lua$") then
-- 加载.lua文件
local moduleName = path:gsub("%.lua$", ""):gsub("/", ".")
local success, err = pcall(function()
require(moduleName)
end)
if not success then
SL:print("加载文件失败:", moduleName, "错误:", err)
else
SL:print("成功加载:", moduleName)
end
end
end
end
end
-- 使用示例:加载GUIExport目录下的所有文件(包含子目录)
loadAllFiles("dev/GUIExport", true)
```
**注意事项:**
1. `lfs`库需要确保在环境中可用
2. 文件路径分隔符使用"/",Windows系统会自动处理
3. `pcall`用于捕获require时的错误,避免单个文件加载失败影响整个流程
4. 只加载`.lua`文件,其他文件类型会被忽略
**如果遇到问题:**
- 检查`lfs`库是否正确安装
- 确认目录路径是否正确
- 查看具体文件的require语句是否有语法错误
不懂的可以问浮生梦尊师!