[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Initial perceptions on the package system
- From: David Manura <dm.lua@...>
- Date: Tue, 13 May 2008 00:23:08 +0000 (UTC)
ketmar writes:
> Gustavo Niemeyer wrote:
> > module() seems a bit tricky to deal with.
> i'm using this code:
>
> kmodule.lua:
> function kmodule (module, name)
> if type(package.loaded[name]) == "userdata" then
> -- emulate "module"
> module._M = module;
> if type(name) == "string" then
> module._NAME = name;
> local pkg = name:match("^(.-%.)[^%.]*$") or "";
> module._PACKAGE = pkg;
> end;
> return module;
> else return false;
> end;
> end;
>
> local xm = { kmodule = kmodule };
> if kmodule(xm, ...) then return xm; end;
Though I haven't had much need to add the _M, _NAME, and _PACKAGE variables to
the external interface, overall that is a reasonable approach. Similar
sentiments are detailed here:
http://lua-users.org/wiki/LuaModuleFunctionCritiqued
You also illustrate the need for the "test against userdata" hack to detect when
a module is run as a script.
>> It'd be nice if "requires" could tell the executed module where it was
>> found somehow (e.g. _FILE)....e.g. read a template or whatever
>> from the same place)
Encoding a binary resource (e.g. image file) in a Lua module is doable (similar
to bin2c) as suggested but I think worth avoiding if possible.
One solution is to reimplement the search function in Lua:
http://lua-users.org/wiki/LuaModulesLoader
It's been requested before and could be a common need. There was mention that
Lua 5.2 will have a package.searchpath function:
http://lua-users.org/lists/lua-l/2008-02/msg00686.html
http://lua-users.org/wiki/LuaFiveTwo
However, package.path/package.cpath hard-code the file extension (e.g. "?.lua"
or "?.so), and you likely want to use many different file extensions, for each
resource type, so maybe package.searchpath is not flexible enough.
I recall Java has such a thing:
http://www2.sys-con.com/ITSG/virtualcd/Java/archives/0205/maso/index.html