[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: require() passing arguments to module?
- From: HyperHacker <hyperhacker@...>
- Date: Sat, 5 Nov 2011 21:08:25 -0600
On Sat, Nov 5, 2011 at 07:14, Roberto Ierusalimschy
>> On Fri, Nov 4, 2011 at 10:10 PM, HyperHacker <firstname.lastname@example.org> wrote:
>> > I feel like this idea has been brought up before, but I don't recall
>> > the consensus. Presently, require() accepts only one argument. Why not
>> > change it to require(name, ...) and pass all additional args on to the
>> > module? The module can then retrieve them from ... just as it would if
>> > you did loadfile(name)(...).
>> Now sure about consensus, but in `loadfile(name)(...)` you are passing
>> the arguments to the loader. Once require loads a module it caches
>> it. So, if another call is later made to require for the same module
>> but with different arguments, the new arguments are ignored because
>> the loader is not re-invoked again. You therefore have in a way a
>> race condition where the behavior depends on the order in which
>> modules are loaded.
> +1 for this answer :)
>> Sometimes I do things like `local X = require 'foo' (...)`, which
>> achieves the desired effect.
> Or, to follow the usual protocol of returning a plain table:
> local X = require 'foo' .init(...)
> (Now the module has the option of allowing its use without parameters.)
> -- Roberto
Aha, that was the problem I was thinking of. I knew there was some
reason it wouldn't work.
I suppose you could take Roberto's example further and turn modules
into "factories" of sorts:
local foo = require('foo').create(some, args, here)
so require('foo') just returns a function that will create an instance
of the foo module. There might be a better name for this pattern?
Sent from my toaster.