lua-users home
lua-l archive

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


very sorry for that, this code is not the one I tested with Lua5.2, I
only typed it into gmail :-(

the real one I test with Lua5.2 is here (I found it in my Temp folder):
local print = print
local module = module
package.preload.mymod = function(...)
    module(...)
    function foo()
        return 123
    end
    function bar()
        return 456
    end
end

local mm = require 'mymod'
print(mm)
--print(mm.foo())
--print(mm.bar())
print(module)

-- cc: cc='d:\lua52\luac -l -l' cc='lua52'


2011/12/29 Patrick Rapin <toupie300@gmail.com>:
> 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)
>