local files = love.filesystem.getDirectoryItems(fdir)
function love.load()
print("Loading...")
for i,v in ipairs(files) do
print("Requiring..."..v)
-- require = files This does not work :,(
end
end
Is there a nice way to require files using a for loop? I tried the above it did not work
You should check first if the file is a .lua file. If it is, strip the ".lua" from the filename and require it. If it isn't, you can either ignore it, or check if it's a folder and require all the files in that folder (using recursion.)
Probably a bad idea to require files that way, since the order of files isn't specified.
However, as an alternative, you could autoload files based on the first attempt to lookup something. I.E. you set the global metatable to have an __index that will look for a file whose name matches the item you're attempting to read.
setmetatable(_G, {
__index = function(_, key)
if love.filesystem.exists(key..'.lua') then
local value = require(key)
rawset(_G, key, value)
return value
end
end,
})
I haven't tested this particular piece of code, but I did something like it in the past. It obviously requires the file loaded to return a value.
-- lib/bar/x.lua
require 'require'
local y = require.relative(..., 'y') -- requires 'lib/bar/y.lua' without having to specify "lib.bar.y"
I did it for a Ludum Dare some time ago so the code is not as clean as I'd like it to be. In particular,I'd make it return a local table instead of overriding the global require.
function love.load()
print("Loading...")
for i,v in ipairs(files) do
print("Requiring..."..v)
v = v:sub(1,-5)
require(fdir..v)
end
gamestate = "intro"
IntroScreen:start()
end
Thank you all for replying, the above code works fine.