lua-users home
lua-l archive

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

On 5 October 2010 13:50, Thijs Koerselman <> wrote:
> On Tue, Oct 5, 2010 at 2:16 PM, steve donovan <>
> wrote:
>> On Tue, Oct 5, 2010 at 1:56 PM, Thijs Koerselman
>> <> wrote:
>> > local require, print = require, print
>> > module 'mymodule'
>> > require 'string'
>> > print(string.format('%s', 'some string'))
>> After your call to module(), the environment of the chunk has changed,
>> and require 'string' isn't clever enough to bring the name 'string'
>> into the module environment. You would have to say 'local string =
>> require 'string'' at this point.
>> This is the kind of weirdness that has led to Lua 5.2 dropping
>> module() altogether - too much messing around with function
>> environments!
> Thanks Steve, I get it. I see that both module and setenv are deprecated in
> 5.2. What is the most basic way to create a module with
> - no pollution of global namespace
> - no prefix required for methods to call each other inside module.
> - no deprecated functions

module/require aren't deprecated in 5.1. In 5.1 you can avoid global
pollution by not calling module(), but returning a module table
instead. The loader would then have to do "local foo = require 'foo'"
to capture your return table.

You said no prefix, this can be done with setfenv, metatables, or
manually pulling functions into the current environment (an import()
helper function could do this).

In 5.2 you could do the same thing in other ways, considering _ENV.

-- mymodule.lua
return function (_ENV)
   _ENV = _ENV or {};
   function exportedfunc1(foo, bar)
   local function privatefunc1(foo)
   return _ENV;

-- requirer.lua
require "mymodule" (_ENV) -- Loads into the current environment
-- OR
local mymodule = require "mymodule" () -- Loads into empty environment
and returns

Obviously having to call a module is a departure from how we do things
today, but this seems the most natural approach to achieve all your

It makes me wonder though if something like this couldn't be built
into 5.2's require() (a second parameter) to compensate for the loss
of module()...