lua-users home
lua-l archive

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


Hello,

in the documentation of Lua 5.2 alpha I found the function
lua_upvaluejoin with the following description:


void lua_upvaluejoin (
  lua_State *L, int fidx1, int n1, int fidx2, int n2 );

Make the n1-th upvalue of the Lua closure at index
fidx1 refer to the n2-th upvalue of the Lua closure
at index fidx2.


I assuming that this function would somehow "connect" the
two upvalues, so that when function 1 updates the upvalue,
function 2 will refer to the updated upvalue and vice versa.

But it seems this is not the case. I tested it with the
following program:


#include <lua.h>
#include <lauxlib.h>

static int upvaluetest_set(lua_State *L) {

  // expecting one argument
  lua_settop(L, 1);

  // load old upvalue
  lua_pushvalue(L, lua_upvalueindex(1));  // 2

  // update upvalue with value given as argument
  lua_pushvalue(L, 1);  // 3
  lua_replace(L, lua_upvalueindex(1));

  // return old upvalue
  return 1;

}

static int upvaluetest_get(lua_State *L) {
  // load and return upvalue
  lua_pushvalue(L, lua_upvalueindex(1));
  return 1;
}

int luaopen_upvaluetest(lua_State *L) {

  // create module table
  lua_settop(L, 0);
  lua_newtable(L);  // 1

  // create closure for upvaluetest.set(...)
  lua_pushliteral(L, "uninitialized-set");  // 2
  lua_pushcclosure(L, upvaluetest_set, 1);  // 2

  // create closure for upvaluetest.get()
  lua_pushliteral(L, "uninitialized-get");  // 3
  lua_pushcclosure(L, upvaluetest_get, 1);  // 3

  // join upvalues
  lua_upvaluejoin(L, 2, 1, 3, 1);

  // register funcitons
  lua_setfield(L, 1, "get");
  lua_setfield(L, 1, "set");

  // return module table
  return 1;

}


I got following results:

Lua 5.2.0 (alpha)  Copyright (C) 1994-2010 Lua.org, PUC-Rio
-> = upvaluetest.get()
uninitialized-get
-> return  upvaluetest.set("One")
uninitialized-get
-> return  upvaluetest.set("Two")
One
-> return  upvaluetest.get()     
uninitialized-get


I expected the last call to return "Two".

It appears lua_upvaluejoin does not make both closures refer
to the same value, but only copy the reference once. Is this
behaviour intended? Would you really need a function for
that, as you could easily write

lua_getupvalue(...);
lua_setupvalue(...);

directly or as a macro.

I'd like to get to know the intention behind the
lua_upvaluejoin function and what it is supposed to do
exactly. Can somebody help me?


Regards
Jan Behrens