lua-users home
lua-l archive

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


Hi,

An odd question maybe, but is there a way to determine whether a lua
state is busy processing a chunk? I have a few places in my code where,
depending on whether the code is being called from lua or directly from
C, I'd like have a different behaviour. A simple example:

Suppose I have a "Point" class in C++, which I've written a binding for
in Lua. To create a new "Point" object on the Lua stack, I've written a
function

Point *PushNewPoint(lua_State *L);

The problem arises if for some reason this function could fail. If it's
being called by Lua (from a script), the proper answer would be to raise
an error using luaL_error. However, if PushNewPoint() is being called
directly from the application, luaL_error will call exit(), causing an
immediate and rather rude termination of the entire application. In this
case, I'd much rather have PushNewPoint() to return a NULL pointer, so
that the calling function can gracefully exit. 

The alternative would be to never have PushNewPoint call luaL_error, but
this results in messy code. An __add metamethod implementation for this
Point class would be something simple and neat like 

static int PointAdd(lua_State *L)
{
	const Point *P1 = GetPoint(L, 1),
			*P2 = GetPoint(L, 2);
	Point *result = PushNewPoint(L);
	
	*result = *P1 + *P2;
	return 1;
}

if these functions can call luaL_error(), while if I'd have to check all
the intermediate pointers and call luaL_error() from here, which is not
only cumbersome, but also not very safe.

Right now, I'm inspecting L->errorJmp. If it's not null, then I'm
probably called from Lua (All scripts are called using lua_pcall) and
luaL_error() should be used. If it's null, then luaL_error() should be
avoided. However, I'm not really comfortable with that - I don't like
using undocumented implementation details. Is there a documented way to
do this?

Kind regards,

Martijn van Buul