[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: import module from zip, like java jar package
- From: zhiguo zhao <zhaozg@...>
- Date: Tue, 4 Jan 2011 14:38:02 +0800
I need extend lua support load module from zip file, refrence to
package.loaders,
I write a module simply can imp this.
It base on luazip, and need LUA_ZPATH env variable or package.zpath variable.
On win32
set LUA_ZPATH=D:\work\luabuild\bin\Win32Debug\a.zip\?.lua;c.zip\?.so;d:\zip.zip\?\init.lua;E:\e.zip\?\init.lua
It will be split every entry to zip file path and a module pattern. ? will be replaced with module name, and so not support yet. now.
And I need to more test, there may be exist bugs.
If l.lua in a.zip, It can be test with below cmd.
luajit -l zloader -e require(\"l\")
-----------------------------------------------------------------------------------------------------
local table,string,os,package = table,string,os,package
local pairs,ipairs,print,loadstring,assert = pairs,ipairs,print,loadstring,assert
local zip = require("zip")
module('zloader')
local htab = {} --zip handle
local ftab = {} --file list
local ztab = {} --zip file with pattern
local function mklibs()
package.zpath = package.zpath or os.getenv('LUA_ZPATH') or ''
for path,pattern in string.gmatch(package.zpath..";", "([^;]*zip)[\\/](.-);") do --split at ;
if not htab[path] then
local z,err = zip.open(path)
if z then
htab[path] = z
ftab[path] = {}
for fn in z:files () do
ftab[path][fn.filename] = path
end
end
end
local t = ztab[path] or {}
if not t[pattern] then t[pattern] = true end
ztab[path] = t
end
return ztab
end
function zloader(modulename)
local ztab = mklibs()
--load module
for path,v in pairs(ztab) do
for pat,_ in pairs(v) do
pat = string.gsub(pat, "%?", (string.gsub(modulename, "%.", "/")))
if ftab[path] and ftab[path][pat] then
local z = htab[path]
local zf = z:open(pat)
if zf then
local s = zf:read('*a')
zf:close()
return assert(loadstring(s))
end
end
end
end
end
-- Install the loader so that it's called just before the normal Lua loader
table.insert(package.loaders, zloader)
Attachment:
zloader.lua
Description: Binary data