[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: export
- From: Matthew Wild <mwild1@...>
- Date: Mon, 23 Nov 2009 13:26:25 +0000
2009/11/23 spir <denis.spir@free.fr>:
> Matthew Wild <mwild1@gmail.com> wrote:
>
>> 2009/11/23 spir <denis.spir@free.fr>:
>> > Hello,
>> >
>> > I'm looking for a straightforward way to define what a module exports -- other than setting all the rest global. Ideally, this would be something like:
>> >
>> > -- module mod
>> > require("mod_test")
>> > __export = {CONST=CONST, config=start_config, test=mod_test.test, do=safe_do}
>> >
>> > CONST = 3.14
>> > start_config = {...}
>> > do = function(...) ... end
>> > safe_do = function(...) ... do(...) ... end
>> >
>> > Then, as you guess, requiring "mod" would export only the content of __export.
>> > Is there method analog to this?
>> >
>>
>> At the bottom of the file put "return __export", it will be used as
>> the return value from require, and saved in package.loaded[modulename]
>> for future calls.
>
> Great! That's exactly what I was looking for. (Didn't think, though, it could be _such_ straightforward).
> By the way, does this means that require (or behing loadfile, or even load) will regard the whole module like a func? maybe taking the module's global namespace as return value if none explicitely defined?
>
By default the module's global namespace is *the* global namespace, so
if you just define global functions and do nothing else then they are
accessible anyway, as globals.
Typically people use module(), which creates a new environment
(namespace as you call it), and module() also sets
package.loaded[modulename] to this environment, so that require() will
return it now and in future (still returning something can overwrite
package.loaded[modulename] though).
If you don't call module(), don't set package.loaded[modulename] and
don't return anything then require() will just return true.
Matthew