lua-users home
lua-l archive

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

I write following code to change the _ENV of a lua function

int lua_setenv (lua_State *L, int index) {
  int i;
  const char *upkey;
  if(!lua_isfunction(L, index)) {
    return 0;
  if(!lua_istable(L, -1)) {
    return 0;
  for(i = 1; ; i++) {
    upkey = lua_getupvalue(L, index, i);
    lua_remove(L, -1);
    if(!strcmp(upkey, "_ENV")) {
      lua_setupvalue(L, index, i);
      return 1;
  return 0;	

the function takes two arguments.
index should be the index of the target lua function.
the function will pop the top of the stack and try to set it as the
_ENV of the target lua function.

After trying such code I found that if I change the _ENV of a lua
function, it will change the _ENV of whole file.
I wonder if there is any way I can only change the _ENV of a certain
lua function without affecting the other part of the script.
THX in advance.