lua-users home
lua-l archive

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


Roberto Ierusalimschy wrote:
>
> > I was thinking something along the lines of all C functions having a
> > special upvalue that is their environment (in the same way as a Lua
> > function).
> 
> That is the whole point. Lua functions will not have any special uvaplue
> that is their environment. They may or may not have an upvalue called
> _ENV, which may or may not be used as its environment.
> 
> 
> > I guess we could say it is index 0 and that new closures
> > inherit the environment (upvalue 0) of the creator. (This is currently
> > how it will work in Lua 5.2 minus the lexical scoping.) The
> > LUA_ENVIRONINDEX would then be:
> > 
> > #define LUA_ENVIRONINDEX  lua_upvalueindex(0)
> > 
> > Now C functions can index the "magic" _ENV local/upvalue in the same
> > way a Lua function can.
> 
> What do you gain with that? How frequently do you create new C functions
> that must inherit the "environment" of its creator, except for the
> obvious case when you are opening a library?

I.e. when you want to support unloadlibrary.

I did exactly what Patrick is suggesting in my Lua dialect back in 2003.
The initial motivation was to support unloading of modules.  Upvalue 0
held a reference to the library which was inherited via pushcclosure.
When that reference was collected, the library was unloaded.

Later I modified it to hold a table in that slot (the library reference
moved into that table) and called that table the "private registry" of
the module:

#define SOL_IDX_REGISTRY        SOL_IDX_STACK(1)        /* global registry */
#define SOL_IDX_PREGISTRY       SOL_IDX_UPVALUE(0)      /* private registry */

> Moreover, I think most C libraries do not use environments. (Of all
> standard libraries, only iolib uses it.) It seems a waste of space to
> keep an extra upvalue for all C functions when only a small fraction of
> them will use it.

One value per C function - peanuts (same as two instructions or so).

Ciao, ET.