二进制模块加载器

lua-users home
wiki

这是一个加载二进制模块的模块加载器示例,就像Lua自带的独立加载器一样。你可以用它来实现更复杂的加载器。(作者: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)


此页面的术语可以改进。这是一个返回“加载器”的“搜索器函数” [1]。(不幸的是,package.loaders 不叫 package.searchers。)此外,“二进制模块”这个术语可能会错误地暗示 Lua 字节码文件;我建议使用手册中提到的“C 库”(或“共享库”)。因此,我建议将页面重命名为“CeeLibrarySearcherFunctionInLua?”(目前此 wiki 上还有四个“*InLua?”页面)。--DavidManura

RecentChanges · preferences
编辑 · 历史
最后编辑于 2009 年 9 月 5 日晚上 10:01 GMT (差异)