lua-users home
lua-l archive

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


On Mon, Oct 7, 2013 at 10:15 AM, Andre Arpin <arpin@kingston.net> wrote:
> This is verbatim from the wiki.
>
> (function()
>   local require = require
>   local print = print
>   local module = module
>   module("yourmodule");
>
>   (function() module("mymodule") end)()
>
>   print(mymodule ~= nil) -- prints false (where is it?)

It's in the global environment, which you don't have any more.

If you add:

local _G = _G

and then change print to

print(_G.mymodule) then it will print true.

> end)();
>
> print(mymodule ~= nil) -- prints true (where did this come from?)

In 5.1, you're back in the global environment.

> I ran it on 5.2 and got this output
>
> false
> Lua: Error while running chunk
> E:\lua\test.lua:12: attempt to call global 'print' (a nil value)
> stack traceback:
> E:\lua\test.lua:12: in main chunk
>
> Lua: Error while running chunk
>
> Does this run as published on 5.1?
> If so is "module" different on 5.2?
>
> Andre

What is different is _ENV, which is set to a table that points to the
the previous global environment. In 5.1, there were just upvalues,
locals and one _G table.

So in 5.2, you wipe out everything in the _ENV table when you call
module without "package.seeall".

Later in the parent scope, the effect lingers. Since module isn't
intended to be nested like this, you'd never see it in real code, as
far as I know.

As has been mentioned, "module" is deprecated because putting things
into the global environment is thought to be a decision of the user
and not the module author. Also, the way that "_ENV" works is
extremely powerful and provides for many of the mechanisms that would
otherwise need "package.seeall" and other such magic.


- Andrew

PS: (function print("hello") end )() is a good way to encapsulate
something within a scope, but it ends up leading to a bunch of ";" and
is more verbose than using "do ... end".

do
   print("hello")
end

To each their own. It just took me a while to figure out what you were
up to, the way that it was written.


PPS: My apologies for assuming that you were new to lua.