Page 1 of 1

Recursive resource loading function

Posted: Wed Apr 24, 2013 2:09 pm
by Santos
Here's a function which loads images and sounds from a folder into a table, with keys based on file names and subfolders in subtables.

If you have a game folder with these files...

main.lua
rainbow.png
sounds/sparkle.ogg
sounds/music/smoothjazz.xm


... and call the function...

loadresources()

... you can then use the resources like this:

love.graphics.draw(rainbow)
sounds.sparkle:play()
sounds.music.smoothjazz:play()


Or you can set a base folder and/or a table for the resources:

resources = {}

loadresources ('sounds', resources)

resources.sparkle:play()
resources.music.smoothjazz:play()



Here's an explanation of how it works:
loadresources.zip
(4.75 KiB) Downloaded 30 times
And here's the function:

Code: Select all

function loadresources(a, b)

    local base_folder, resource_table

    if type(a) == 'string' then
        base_folder = a
    elseif type(b) == 'string' then
        base_folder = b
    else
        base_folder = ''
    end

    if type(a) == 'table' then
        resource_table = a
    elseif type(b) == 'table' then
        resource_table = b
    else
        resource_table = _G
    end

    local function load_directory(folder, place)

        for _, item in pairs(love.filesystem.enumerate(folder)) do

            local path = folder..'/'..item

            if love.filesystem.isFile(path) then
                local name, ext = item:match('(.+)%.(.+)$')

                if ext == 'png' or ext == 'bmp' or ext == 'jpg' or ext == 'jpeg' or ext == 'gif' or ext == 'tga' then
                    place[name] = love.graphics.newImage(path)

                elseif ext == 'ogg' or ext == 'mp3' or ext == 'wav' or ext == 'xm' or ext == 'it' or ext == 's3m' then
                    place[name] = love.audio.newSource(path)
                end

            else
                place[item] = {}
                load_directory(path, place[item])
            end
        end
    end

    load_directory(base_folder, resource_table)

end

Re: Recursive resource loading function

Posted: Wed Apr 24, 2013 2:31 pm
by Robin
If you have a lot of images, sounds and music, it might be a good idea to do lazy loading instead, so it would only load an image if you actually try to draw it, for example.

By the way, I would not advocate calling loadresources() without a table argument, as that pollutes the global table.

This has been my mandatory nitpicking session. :)

Re: Recursive resource loading function

Posted: Thu Apr 25, 2013 3:55 am
by Santos
Good points! :)

For loading resources like that, you could do something like this: http://santos.nfshost.com/proxy.html

Alternatively, threads might be a good option too, as used in love-loader: https://github.com/kikito/love-loader

That's true about it taking up space in the global table, unless of course you have all your resources in one folder! :ultraglee: