Skip to content

Instantly share code, notes, and snippets.

@armornick
Created September 2, 2012 15:17
Show Gist options
  • Save armornick/3600378 to your computer and use it in GitHub Desktop.
Save armornick/3600378 to your computer and use it in GitHub Desktop.
Love2d Resource Manager
-- exporting table
local exports = {}
-- table containing the resources
local resources = {}
local imagepath = "image"
local soundpath = "sounds"
local fontpath = "fonts"
-- add image to resource manager
local function addImage(id, img)
if not img then img = id end
resources[id] = love.graphics.newImage(img)
return resources[id]
end
local function isWav (filename)
local s, e = string.find(filename, ".+%.wav")
end
-- add sound to resource manager
local function addSound(id, snd)
if not snd then snd = id end
if isWav(snd) then
resources[id] = love.audio.newSource(snd, 'static')
else
resources[id] = love.audio.newSource(snd)
end
return resources[id]
end
-- add font to resource manager
local function addFont(id, fnt, size)
if not fnt then fnt = id end
if not size then size = 14 end
resources[id] = love.graphics.newFont(fnt, size)
return resources[id]
end
-- get a resource from the resource table
local function get(id, objType)
local resource = resources[id]
if not resource then return nil end
if ojbType then
assert(resource:typeOf(objType))
end
return resource
end
-- remove extension from file name
local function removeExtension(filename)
local s, e, name = string.find(filename, "(.+)%..*") -- see: http://www.lua.org/manual/5.1/manual.html#5.4.1
return name
end
local function isValidFile(filename)
local s, e = string.find(filename, ".+%..+")
if s then return true else return false end
end
-- recursively scan directory for files
-- and execute the callback on the file
local function loadDirectory(dir, callback)
if string.find(dir, ".*%.svn") then return end
local lfs = love.filesystem
if not lfs.exists(dir) then return end
local files = lfs.enumerate(dir)
for i, v in ipairs(files) do
local file = dir.."/"..v
if lfs.isFile(file) and isValidFile(v) then
callback(removeExtension(v), file)
elseif lfs.isDirectory(file) then
loadDirectory(file, callback)
end
end
end
-- load every available resource
local function loadAll()
loadDirectory(imagepath, addImage)
loadDirectory(soundpath, addSound)
loadDirectory(fontpath, addFont)
end
loadAll()
-- add functions to export module
exports.get = get
exports.resource = get -- PLACEHOLDER
-- return module
return exports
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment