Page 1 of 1
Require all files in a directory
Posted: Sat Sep 13, 2014 4:54 pm
by Psyk
How would I require all files in a directory?
Entities - Folder
entity.lua
potion.lua
Would I be right if I did this?
Code: Select all
function includeAllEnts()
local directory = "entities"
local entities = love.filesystem.enumerate(directory)
for i, e in ipairs(entities) do
require(e)
end
end
Re: Require all files in a directory
Posted: Sat Sep 13, 2014 5:49 pm
by Robin
Untested, but I'd say:
Code: Select all
function includeAllEnts()
local directory = "entities"
local entities = love.filesystem.enumerate(directory)
for i, e in ipairs(entities) do
require(directory .. "." .. e)
end
end
Re: Require all files in a directory
Posted: Sat Sep 13, 2014 6:04 pm
by Psyk
Robin wrote:Untested, but I'd say:
Code: Select all
function includeAllEnts()
local directory = "entities"
local entities = love.filesystem.enumerate(directory)
for i, e in ipairs(entities) do
require(directory .. "." .. e)
end
end
I get the lua error attempt to call field 'enumerate' a nil value.
Re: Require all files in a directory
Posted: Sat Sep 13, 2014 6:58 pm
by rmcode
Re: Require all files in a directory
Posted: Sat Sep 13, 2014 7:06 pm
by Psyk
Thanks for letting me know that the enumerate function was renamed!
I thought of something else that works the same and gets the job done. Thanks for your help!
Working Code:
Code: Select all
require "love.filesystem"
function includeAllEnts()
local dir = "entities"
local entities = love.filesystem.getDirectoryItems(dir)
for k, ents in ipairs(entities) do
trim = string.gsub(ents, ".lua", "")
require(trim)
end
end
Re: Require all files in a directory
Posted: Sun Sep 14, 2014 1:03 pm
by undef
Shouldn't it rather be:
require(
dir .. "/" .. trim) in this code:
Code: Select all
function requireDirectory( dir )
dir = dir or ""
local entities = love.filesystem.getDirectoryItems(dir)
for k, ents in ipairs(entities) do
trim = string.gsub( ents, ".lua", "")
require(dir .. "/" .. trim)
end
end
Otherwise this should only require all files in the root directory, if I'm not mistaken.
I also think passing the directory as a parameter is convenient.
You don't need to require love.filesystem as well, all love modules are loaded unless deactivated in the config file.