lua-users home
lua-l archive

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


hello, Geoff Leyland <geoff_leyland@fastmail.fm>.

On Thu, 6 Sep 2007 19:52:59 +1200
Geoff Leyland <geoff_leyland@fastmail.fm> wrote:

> Does anyone have any suggestions as to how to achieve the same thing  
> (work out if we're being run as someone else's module or as a top- 
> level script) a better way?

here's my code. it works in Lua 5.1+

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;

and usage:
local mymodule = {};

function mymodule.MyFunc ()
...
end;

...
...

if kmodule(mymodule, ...) then return mymodule; end;


and then:
local mymodule = require "mymodule";

i don't like to pollute global namespace. %-)