lua-users home
lua-l archive

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

On Mon, May 28, 2007 at 08:12:58PM -0400, Tim Hunter wrote:
> Jerome Vuarand wrote:
> >In your Lua example, the common state is stored as an upvalue. You can
> >also have upvalues in C. But you can also achieve the same effect with a
> >function environment, and in your case, I think a function environment
> >is more suited. 
> Okay, I understand your example for using the environment, and thank you 
> Mr. Vuarand very much for the code!
> However, I'd like to also understand using lua_pushcclosure as well, as 
> suggested by Mr. Roberts and Sr. de Figueiredo. I understand how to use 
> lua_pushcclosure for a single function but how would I use it to define 
> two functions that share an upvalue? Do I just push the seed value on 
> the stack and then call lua_pushcclosure for "srand" and then push the 
> seed value again and call lua_pushcclosure again for "rand"?

I think Jerome's right the the fenv is more suited. I forgot there isn't
a one-shot for sharing the same upvalue among multiple c functions. I
was thinking of luaL_openlib(), but it requires the seed to be in a
table to be shared.

> long seed = 12345;
> lua_pushinteger(L, seed);
> lua_pushcclosure(L, srand, 1);
> lua_pushinteger(L, seed);
> lua_pushcclosure(L, rand, 1);

You have to do more like
lua_pushinteger(L, DEF_SEEED)
lua_setfield(L, -2, "seed");
lua_pushvalue(L, -1);
lua_pushcclosure(L, seedfn, 1);
lua_pushvalue(L, -1);
lua_pushcclosure(L, randfn, 1);

luaL_openlib() does some of this work for you, but not making the table.

Then in seedfn you get the table as upvalue 1, and set the "seed" field.

In randfn you get the table as upvalue 1, and get/update the "seed"