lua-users home
lua-l archive

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

On Sat, Feb 18, 2012 at 9:19 AM, Tom N Harris <> wrote:
> On 02/17/2012 03:53 AM, John Tan wrote:
>> 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.
> I believe what you want is lua_upvaluejoin. If you just change the value,
> then all other functions that share that upvalue will also be changed.
> lua_upvaluejoin changes the upvalue reference. The tricky part is that the
> new reference must also be the upvalue of another function.
> [1]
> --
> - tom

After inspecting the code of lua_upvaluejoin()
I decide to write an API myself...
here is the api i write

LUA_API void lua_upvalueref (lua_State *L, int fidx, int n) {
  LClosure *f1;
  UpVal **up1 = getupvalref(L, fidx, n, &f1);
  UpVal *uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), NULL, 0)->uv;
  api_checknelems(L, 1);
  uv->v = &uv->u.value;
  setobj(L, uv->v, L->top);
  *up1 = uv;
  luaC_objbarrier(L, f1, uv);