[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: [ANN] Lua 5.2.0 (work4) now available
- From: Mark Hamburg <mark@...>
- Date: Sat, 7 Aug 2010 10:02:41 -0700
Require only executes the defining file once, so for it to return multiple values, it would need to store multiple values in the loaded table. It could do so. It could even do so in a way that optimizes for the single result case. But it doesn't.
And having observed that require doesn't return multiple values, it then doesn't make that much sense to define multiple modules per file except in the less common predefinition case since require will go hunting for a single file for anything that isn't already loaded. In the predefinition case, what one perhaps needs is:
function() package.module( name )
local M = package.loaded[ name ]
if M == nil then
M = { }
package.loaded[ name ] = M
end
return M
end
Then you can write:
local M1 = package.module "FirstPreloadModule"
function M2.foo() print "FirstPreloadModule.foo" end
function M2.baz() print "FirstPreloadModule.baz" end
local M2 = package.module "SecondPreloadModule"
-- etc
For Lightroom, we do support multiple modules per file but we did this to support cases where modules needed local variable cross-connects and we implemented it by having a manifest file describing how to map module names to the files containing the modules and an export function which actually registered the module for the rest of the world to see. Then our import function (essentially require) would handled requests for unloaded modules by looking in the manifest to find the appropriate script to run, running that script, and then looking for the needed value to have been added to the module table.
In retrospect, however, we rarely used this multi-export capability and the simpler model of one module per script found by name seems much preferable.
Mark
P.S. If I were going to put effort into evolving things it would probably be toward providing support for private modules that can only be accessed by closely related public modules. For example, if we look inside directories for appropriate scripts, one could insist that both C and Lua modules with names beginning with an underscore would only be visible to other modules in the same directory. This could presumably be implemented through a more complicated require implementation involving custom environments and custom versions of the require function.