lua-users home
lua-l archive

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

> 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? For the "obvious case",
there will be support through luaL_registry or similar. For the other
few cases, you may just define the following macro:

  #define pushcfunctionwithenv(L, f) \
      lua_pushvalue(L, lua_upvalueindex(1)); \
      lua_pushcclosure(L, (f), 1)

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. Similarly, it seems a waste of complexity to keep
all this apparatus when it is not used that often and we can get the
same results without it.

-- Roberto