lua-users home
lua-l archive

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


Duck wrote:
>> An alternative would be to replace:
>> 
>>  loadstring(modulecode)(modulename)
>> 
>> by:
>> 
>>  package.preload[modulename] = loadstring(modulecode)
>>  require(modulename)
> 
> Yep, that's what I want.
> 
>> Just out of curiosity, why do you want to use loadfile/loadstring
>> rather than require ?
> 
> I wanted to void having to write a loader for require...but as you
> show above, that 'loader' is as simple as using package.preload[]. 

Writing a module 'searcher' for require can be straightforward (see
[1][2] for examples). If I understand correctly, what you're trying to
achieve is to load modules directly from memory. If the location of the
module can be inferred from its module name, adding a custom searcher to
package.loaders can make your code even simpler since you wouldn't have
to preload the modules yourself. Many situations from modules extracted
from a Windows EXE file resource to modules retrieved from the Net can
be easily implemented with a searcher.

> Your way is better because it makes it possible to do this:
> 
>   package.preload[modulename] = loadstring(modulecode)
>   . . . arbitrary amount of time or space in between . . .
>   require(modulename)
> 
> which also means that the module needn't actually get require()ed
> unless and until it is wanted. My way effectively forces a require()
> whether strictly needed or not.  

The searcher solution allows to delay-load modules too. Actually even
the loadstring could be delayed. That could not be an advantage though,
depending on your situation.

[1] http://lua-users.org/wiki/LuaModulesLoader
[2] http://lua-users.org/wiki/HashedModulesLoader