Lua Modules Loader

lua-users home
wiki

Here is an example of a module loader that simply load Lua modules, just like the standalone loader provided by Lua. You can use it to implement more complex loaders. (JeromeVuarand)

module(..., package.seeall)



local function load(modulename)

  local errmsg = ""

  -- Find source

  local modulepath = string.gsub(modulename, "%.", "/")

  for path in string.gmatch(package.path, "([^;]+)") do

    local filename = string.gsub(path, "%?", modulepath)

    local file = io.open(filename, "rb")

    if file then

      -- Compile and return the module

      return assert(loadstring(assert(file:read("*a")), filename))

    end

    errmsg = errmsg.."\n\tno file '"..filename.."' (checked with custom loader)"

  end

  return errmsg

end



-- Install the loader so that it's called just before the normal Lua loader

table.insert(package.loaders, 2, load)

See Also


RecentChanges · preferences
edit · history
Last edited January 8, 2009 4:45 pm GMT (diff)