lua-users home
lua-l archive

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

 > > On page 254 of the Blue PIL, there's a nice example of using 
 > > a fresh environment to share information among functions in a library.
 > > One thing I'm not clear on: whose responsibility is it to restore the
 > > previous environment?  The example doesn't show the environment
 > > being restored.  Is it somehow restored magically?  Does 'require'
 > > reset the environment when it's finished?  Or is the example wrong,
 > > and is it up to me to restore the environment in my own code?
 > It is never restored. What was changed was the environment of the
 > running function, luaopen_foo (in its Lua incarnation). This function
 > opens the library (which inherits its environment) and returns. It will
 > keep its changed environment for ever (which means until being collected
 > as garbage, after returning to 'require').

What about the (probably anonymous function) which called 'require'
which called luaopen_foo?  Does its environment change?

Let me see if I can summarize:

  Associated with any lua_State *L is an environment.

  This environment can be observed or replace by using lua_pushvalue
  or lua_replace with LUA_ENVIRONINDEX.

  Associated with every Lua function is an environment.  If that
  function is created by lua_pushcclosure(L, f, n), the initial
  environment is the one associated with L.  

All this I understand.  What I don't understand is this: when 
I call lua_replace(L, LUA_ENVIRONINDEX), which *functions'*
environments are changed?  Is it only the youngest active function
called with lua_call, or can other functions' environments change, too?

Another way to ask the question:  suppose I register a function "foo":

  static int lfoo(lua_state *L) { ... }

  ... stuff[] = { 
    { "foo", lfoo }, 

  { ... luaL_register(L, NULL, stuff); ... } 

Here's the $64 question: can any caller of foo observe whether foo
contains a call to lua_replace(L, LUA_ENVIRONINDEX)?