lua-users home
lua-l archive

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


Rici Lake <lua@ricilake.net> [2007-03-25 23:36:16]:

> Petr Stetiar wrote:
> >The problem happens in my C lua_get_function(), which calls lua_getfield()
> >about 200 times per minute. 
> >
> >int lua_get_function(char *function)
> >{
> >	... snip ...
> >	lua_getfield(L, LUA_GLOBALSINDEX, function);
> >	... snip ...
> >}
> 
> Do you check to make sure that there was a hook with that name? It's 
> hard to tell from your snipped code.

I think, that I do. Please take a look at code below.

> You should be doing something like:
> 
>   lua_getfield(L, LUA_GLOBALSINDEX, function);
>   if (!lua_isnil(L, -1)) { ... call the function ... }
>   else return 0;  /* Or something to indicate there was no function */
> 
> Also, you might want to use lua_pcall when you call the function. (Or 
> make sure that the function call is within a protected call.)

It's something like this:

int lua_get_function(char *function)
{
	lua_getfield(L, LUA_GLOBALSINDEX, function);
	if (!lua_isfunction(L, -1)) {
		return FALSE;
	}

	return TRUE;
} 

int lua_event_generic(char *event_name, char *event_text, int param)
{
	int ret = 0;
	char fnc[MAX_PATH] = {0};
	char err[MAX_PATH] = {0};

	_snprintf(fnc, MAX_PATH-1, "gabenie_event_%s", event_name);
	_snprintf(err, MAX_PATH-1, "error gabenie_event_%s()", event_name);

	if (!lua_get_function(fnc)) {
		return ret;
	}

	...snip...

	lua_pushstring(L, event_text);
	ret = lua_pcall(L, 1, 1, 0);

	...snip...

	if (ret != 0) {
		lua_error_box(err);
		return ret;
	}

	return (int)lua_tointeger(L, -1);
}

Thanks. -- ynezz