Binary Modules Loader

lua-users home
wiki

Here is an example of a module loader that loads binary 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 DLL

  local symbolname = string.gsub(modulename, "%.", "_")

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

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

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

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

    if file then

      file:close()

      -- Load and return the module loader

      local loader,msg = package.loadlib(filename, "luaopen_"..symbolname)

      if not loader then

        error("error loading module '"..modulename.."' from file '"..path.."':\n\t"..msg, 3)

      end

      return loader

    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 binary loader

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


The terminology on this page could be improved. This is a "searcher function" that returns a "loader" [1]. (Alas, package.loaders is not named package.searchers.) Also, the term "binary module" might wrongly imply a Lua bytecode file; I suggest "C library" as in the refman (or "shared library"). So, I suggest renaming the page "CeeLibrarySearcherFunctionInLua?" (there are currently four other "*InLua?" pages on this wiki). --DavidManura

RecentChanges · preferences
edit · history
Last edited September 6, 2009 3:01 am GMT (diff)