lua-users home
lua-l archive

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

Peter wrote:

> Interesting code.
> But what I want to do is keep the value, so I can issue a lua_call()
> on.

Ah, in that case, you need to stash a reference to the value somewhere:

static int setTimer(lua_State *L)
     if ( lua_isnumber( L, 1 ) )
          g_waitTime = lua_tonumber( L, 1 );

     // lua_typename( L, lua_type( L, 2 ) )
     // returns "function" which is what I want :)

     lua_settop(L, 2);   /* as before, zap extra args if any */
     g_waitFnRef = lua_ref(L, 1);  /* make sure to lock the reference */

     return 0;

// and later on

static void doTimer(lua_State* L)
     if (lua_getref(L, g_waitFnRef)) {
          if (lua_call(L, 0, 9))   {     /* need to be careful about errors
               // report an error, somehow
     else {
          // turns out the reference was never set

// and much later on

static void disposeTimer(lua_State* L)
     lua_unref(L, g_waitFnRef);
     g_waitFnRef = LUA_NOREF;

// make sure you initialise g_waitFnRef to LUA_NOREF, *not* to 0.
// Otherwise, you'll regret it. I did.


PD: I actually recommend not putting stuff like that in globals, since it
is relative to a lua_State. Using globals means that whatever you write
will only work in a single lua_State, which may prove limiting later on.
Also, I don't like globals. :-) However, the mechanics of that are too
large for the margins of this e-mail.