Below is an excerpt from the game template I use... Keep in mind I didn't trim it down so you'd have to edit to suit, but here it is nonetheless. What happens is I pass a folder to
dbug.enumFiles which selects based on
lib boolean, sends to
requireFiles, and
pcall requires everything and returns as a table. Not sure if it helps, but this is what I do for quick loading. Probably not the best method, but works for me.
Also for reference dbug.print's arguments are: msg(string), prefix(string), force(bool)
Code: Select all
local function getFileExtension(path)
return path:match("^.+(%..+)$")
end
local function requireFiles(files, folder)
local countPass = 0
local tbl = {}
for _, file in ipairs(files) do
local reqPath = file:gsub('/', '.')
local name = file:sub(#file-7, #file-4)
if name == 'init' then name = file:sub(#folder+2, #file-9) end
reqPath = reqPath:sub(1, #reqPath-4)
local success, err = pcall(require, reqPath)
dbug.print(string.format('"%s" from "%s"', name, file), success and '++' or '**')
if success then tbl[name] = err
else dbug.print('\t' .. err, '**', true)
end
end
dbug.print()
return tbl
end
function dbug.enumFiles(folder, file_list, lib) -- lib = true means only loads folders with init inside
dbug.print(string.format('ENUM: %s (%s)', folder, lib and 'modules' or 'files'))
local file_list = file_list or {}
local lib = lib or false
local items = lfs.getDirectoryItems(folder)
for _, item in ipairs(items) do
local file = folder .. '/' .. item
if not lib and getFileExtension(file) == '.lua' and lfs.isFile(file) then -- load file
table.insert(file_list, file)
elseif lfs.isDirectory(file) then
if lfs.isFile(file..'/init.lua') then -- load module
table.insert(file_list, file..'/init.lua')
else -- recursive search
dbug.enumFiles(string.format('%s/%s', folder, file), file_list, lib)
end
end
end
dbug.print(string.format('\t%s %s found...', #file_list, lib and 'modules' or 'files'))
return requireFiles(file_list, folder)
end