Lua 模組載入器

lua-users home
wiki

以下是一個簡單載入 Lua 模組的模組載入器範例,就像 Lua 提供的獨立載入器。您可以使用它來實作更複雜的載入器。(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)

請參閱


最新變更 · 喜好設定
編輯 · 歷程
最後編輯時間 2009 年 1 月 8 日下午 5:45 GMT (diff)