lua-users home
lua-l archive

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


Use the registry Luke... (and light userdata)

Setup the hook :
	// Get in the registry a table with key=&my_hook (create it if needed)
	lua_pushlightuserdata(L, &my_hook);
	lua_gettable(L, LUA_REGISTRYINDEX);
	if (lua_isnil(L, -1)) {
		lua_newtable(L);
		lua_pushvalue(L, -1);
		lua_pushlightuserdata(L, &my_hook);
		lua_settable(L, LUA_REGISTRYINDEX);
	}

	// Set entry with key=Current thread to starttime
	lua_pushthread(L);
	lua_pushnumber(L, starttime);
	lua_settable(L, -3);
	lua_sethook(L, my_hook, ...);

In the hook :
	// Get the table for this hook
	lua_pushlightuserdata(L, &my_hook);
	lua_gettable(L, LUA_REGISTRYINDEX);

	// Get the entry for this thread
	lua_pushthread(L);
	lua_gettable(L, -2);

	// And get the startime value
	starttime = lua_tonumber(L, -1);

Be carreful, this code wasn't tested, but I'm pretty sure you can found
errors in, but the idea is here...

Tom

On Mon, Oct 09, 2006 at 11:50:00PM +1000, David Burgess wrote:
> I was thinking of using  lua_sethook() to call a function
> that checks how how much time has elapsed since the
> hook was set. I was intending to use this as a kill the
> thread when it has been running for too long. So I need
> to keep a start time variable e.g. time_t start = time();
> 
> The lua_sethook() function does not let me pass this value
> so the only way I can store the start time is in Lua, I cant
> see how to store in C in a re-entrant(threadsafe) manner.
> I would like keep the time on the C side to save the table
> lookup on each hook call, Does anyone have a good way
> of doing this without using static or global variables or C++?
> 
> And maybe in 5.2 could the prototype maybe be change from
> 
> int lua_sethook (lua_State *L, lua_Hook func, int mask, int count);
> 
> to
> 
> int lua_sethook (lua_State *L, lua_Hook func, void* userdata, int
> mask, int count);
> 
> have the hook function as
> 
> typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar, void* userdata);
> 
> Or is this change not required and is their an easier way to get
> C side data into a hook function?
> 
> DB

-- 
Thomas Lavergne                       "Le vrai rêveur est celui qui rêve
                                       de l'impossible."  (Elsa Triolet)
thomas.lavergne@reveurs.org                           http://reveurs.org