lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Thomas Lauer wrote:
> Wouldn't it be nice if the io module were layered and accepted,
> within the functional framework already defined, "drivers" which
> implement the actual I/O? These pluggable drivers would use the
> infrastructure of the io module, both internally (ie code in
> liolib.c) and externally. File access via the C runtime (as already
> implemented in io) would be included by default but this would just
> be one of many possible drivers which can use the io framework.      

In my little Lua game engine, I do exactly that. I replace io.open with
a custom function that will check a series of potential loaders, so that
any module using io.open can transparently access raw files, gzipped
files, files in a bigfile/archive (a .zip or whatever format may be
suited), or from the resources in a exe or dll. I just make sure all my
loaders return a file object with roughly the same API as the default
Lua files. Here is the code I use:

local zip = require_opt 'zip'
local gz = require_opt 'gz'local io_open = io.open

local io_open = io.open
io.open = function(filename, mode, ...)
    local file,msg
    if zip and (not mode or not mode:find("w")) then
        file,msg = zip.openfile(filename:gsub('\\', '/'), ...)
    end
    if not file and gz and (not mode or not mode:find("w")) then
        file,msg = gz.open(filename..".gz", mode)
    end
    if not file then
        file,msg = io_open(filename, mode)
    end
    if not file then
        return nil,msg
    else
        return file
    end
end

So far I haven't felt the need to have a 'framework' implemented in io
library, but next time I add a loader I'll probably refactor that to use
an array like the one used by require.