lua-users home
lua-l archive

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


Diego Nehab wrote:
> This default behavior is to ensure users can use require in two ways
>     local a = require"a"
>     a.b()
> and
>     require"a"
>     a.b()
> and it doesn't bother me too much. Is it easy to override (besides
> rewriting module())?

There is no need to use module() at all, if you don't want to spill
into the global namespace.

  local function internal() ... end
  function foo() ... internal() ... end   -- module-internal call (good)
  function bar() ... foo() ... end        -- intra-module call (avoid)

  local _M = {}
  local function internal() ... end
  function ... internal() ... end
  function ... ... end
  return _M

In fact it's more efficient, because there is no indirection for the
globals table (modified by module()). The little additional syntax
is quite useful, because you can easily spot exported functions.

Note that the intra-module calls to exported functions (
are rare in practice. If you have one of these, it's a good idea
to refactor it to use a common module-internal (local) function
(it's faster, too).

For C modules, replace:
  ... push upvalues ...
  luaL_openlib(L, "modulename", funcs, nupvalues);
  return 1;  /* returns the table created and filled by luaL_openlib */

  ... push upvalues ...
  luaL_openlib(L, NULL, funcs, nupvalues);
  return 1;  /* returns the created table that is still on the stack */

So it's up to the module author to decide which way his/her module
can be loaded. I'm a proponent of the 'clean namespace' camp,
so you can guess what I would recommend.