lua-users home
lua-l archive

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

On 5 October 2010 14:36, Thijs Koerselman <> wrote:
> On Tue, Oct 5, 2010 at 3:10 PM, Matthew Wild <> wrote:
>> 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).
> Yes I already know some ways in 5.1 like the ones you mentioned. I was
> specifically interested in how this is supposed to be done in 5.2 with the
> deprecation of those functions.
>> 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)
>>   end
>>   local function privatefunc1(foo)
>>   end
>>   return _ENV;
>> end
>> -- 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
>> goals.
> Hmm that doesn't excite me very much no.
>> 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()...
> It looks to me like something along those lines would be helpful. I still
> don't get why those functions are deprecated in 5.2 and the better
> alternative would be, but probably I'm just missing the bigger picture.

What do you call the "better alternative"? Your original email gave a
very good example of the problems with require/module() in 5.1. A
module that simply returns its module table (not the magic version I
gave above, but the one Steve did) would work as-is in both 5.1 and
5.2. It also doesn't pollute the global namespace, something most
people regard as bad practice (which is why module() has been
deprecated, since it encourages this).

However that approach of returning the module table doesn't allow you
to import the module's functions into the current environment as you
requested, which is what my example aimed to do. An alternative to
(but slightly less efficient than) my syntax would be to define an
import() function which copies the returned module table into the
current environment.