lua-users home
lua-l archive

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


Again, have you tried your code ?
Really, I can't follow you. Your example code below causes two runtime errors :

> local module = module
> local oldenv = _ENV
> local newenv = {}
> local _ENV = newenv
> function mymod(...)
>    module(...)
>    function abc() end
>    function def() end
> end
> _ENV = oldenv
> package.preload.mymod = mymod
> local m = require 'mymod'     --> error: module 'mymod' not found
> assert(not m.abc and not m.def)
> assert(m == module)
> assert(newenv.abc and newenv.def)  --> error: assertion failed

The require function fails because package.preload.mymod was affected to nil !
At line 11, "mymod" evaluates to oldenv.mymod, different from the
previous newenv.mymod function.
And if you correct that line : "package.preload.mymod = newenv.mymod",
the assertion failed at the last line.
Hopefully in fact, since I couldn't imagine why this assertion should
be true (the reason I wanted to try out).
Because when mymod is called (from the require function), the _ENV
variable declared at line 4 has been affected to oldenv.
In line 10 is corrected to "local _ENV = oldenv", it works.

Have you really understood that the example is the exact equivalent to
the following version ?

local module = _ENV.module
local oldenv = _ENV
local newenv = {}
local _ENV = newenv
function _ENV.mymod(...)
   module(...)
   function _ENV.abc() end
   function _ENV.def() end
end
_ENV = oldenv
_ENV.package.preload.mymod = _ENV.mymod
local m = require 'mymod'
assert(not m.abc and not m.def)
assert(m == module)
assert(newenv.abc and newenv.def)