lua-users home
lua-l archive

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


Hi,

I wrote the following macros which I use in most functions that call Lua.
They've proved very useful and have caught quite a few stack "leaks" as well
as drawing my attention to the way that the lua_xxlibopen() functions leave
a value on the stack.


#ifdef _DEBUG
#define	STACKCHECKSTART(ls)		int __stackTopEnd_##ls = 0; int
__stackTopStart_##ls = lua_gettop(ls);
#define	STACKCHECKEND(ls)		STACKCHECKENDPLUS(ls, 0)
#define STACKCHECKENDPLUS(ls,a)	assert((__stackTopEnd_##ls = lua_gettop(ls))
== __stackTopStart_##ls + a);
#else
#define	STACKCHECKSTART(ls)
#define STACKCHECKEND(ls)
#define STACKCHECKENDPLUS(ls,a)
#endif

Example

void egfunction(lua_State *ls)
{
	STACKCHECKSTART(ls)

	<use the Lua API>

	STACKCHECKEND(ls)
		- or -
	STACKCHECKENDPLUS(ls, 2)	/* Should leave fn with 2 extra
values on Lua stack */
	return;
}

Mark.

-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br] On Behalf Of Matthew Harmon
Sent: 13 September 2004 14:29
To: 'Lua list'
Subject: Proper Stack Cleaning



I recently activated the runtime checks/tests and found that one of my bugs
was likely due to a stack overflow.  I soon realized that there were some
operations I was performing that left values on the stack.  For example,
loading libraries with lua_xxxlibopen(), etc. may push values onto the
stack, according to lua_gettop() anyway.  In fact, by the time I got to do
any "real" work, the stack had 13 items on it.

In the examples and docs, I don't see mention of cleaning up the stack after
operations like these.  Is it good practice to simply do a lua_settop(l, 0)
after a bunch of such operations?

Also, what is the proper procedure for enabling the runtime checks?  I
manually included luauser_tests.h and added ltests.c to my project.  That
seemed to work, but I'm not sure if that is the recommend method.