lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sun, 11 May 2008 18:30:10 -0300
Gustavo Niemeyer <gustavo@niemeyer.net> wrote:

> - module() seems a bit tricky to deal with.  I've specifically
> stumbled upon the fact that it either hides the global environment,
> or it pollutes the module namespace (with package.seeall).  I've also
> missed the "import locality" common in other languages; in Lua, if
> one module requires something, everything else can see the same
> module.  I'm trying to invent some conventions to minimize these
> details, but it'd of course be awesome to have the standard mechanism
> dealing with it, as it'd encourage good practices by default.
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;
-- end of kmodule.lua --


and then for a new module:
mymodule.lua:
require "kmodule";

local mod1 = require "mod1";
...
local mymodule = {};
...
local function XYZ ()
...
end;
...
function mymodule.ABC ()
...
end;
...

if kmodule(mymodule, ...) then return mymodule; end;
print("we aren't require()'d, just executed!");
-- end of mymodule.lua --

and so for mod1.


this scheme doesn't pollutes _G, one can debug module just by invoking
it with "lua mymodule.lua [agrs]", no package.seeall used, other modules
can't see locally required one (but can require() it too, and it will
be loaded only once), etc.

it's not the best way to do the things, but it works good. also one has
a clear visual indication of exported functions -- and one can write it
as:
...
local mymodure = { exportfn0, exportfn1, ...);
if kmodule(mymodule, ...) then return mymodule; end;
...
to make it even clearer.

P.S. this code based on the code from wiki and this list, i just don't
remember copyrights and so. sorry.