lua-users home
lua-l archive

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


Good advice all! I use the following code in all my C API projects for Lua
stack tracing:

static void luaX_showstack(lua_State* L, const char* label = 0)
{
	int top = lua_gettop(L);
	ATLTRACE2("Stack top: %i. %s\n", top, label);
	// 0 - nil; 1 - boolean; 2 - light UD; 3 - number; 4 - string; 5 -
table; 6 - function; 7 - UD; 8 - thread;
	for (int i = -1; i >= (-top); i--)
	{
		lua_pushvalue(L, i);
		const char* tn = lua_tostring(L, -1);
		lua_pop(L, 1);
		ATLTRACE2("++ Stack index: %i, (%s)%s\n", i, lua_typename(L,
lua_type(L, i)), tn);
	}
}

ATLTRACE2 is the trace macro for the ATL library I use (Windows environment)
but you should be able to find a suitable substitute in any "C" environment.

-----Original Message-----
From: lua-bounces@bazar2.conectiva.com.br
[mailto:lua-bounces@bazar2.conectiva.com.br] On Behalf Of Dolphin
Sent: 11 March 2009 15:28
To: lua@bazar2.conectiva.com.br
Subject: Re: Unable to access table using lua after creation of table in C

I would suggest looking at http://www.lua.org/pil/24.2.html (The Stack).
Most
of the lua C API operates on values on the stack.  I use
http://pgl.yoyo.org/luai/i/_
as a reference when I need to remember what the functions do.  Stack
programming
takes a bit of getting used to, and some of the lua C api may do thinks you
are
not expecting until you get a bit more comfortable with it.

To create a new global table named "tablename" in C you can do:

lua_newtable(L);                    //[{}]
lua_setglobal(L, "tablename");      //

If you want to create the table AND add a c function to it.

lua_newtable(L);                    //[{}]
lua_pushcfunction(L, someFunc);     //[somefunc, {}]
lua_setfield(L, -2, "someFuncName");//[{somefuncName=somefunc}]
lua_setglobal(L, "tablename");      //[]

if you need to access an existing table and add a c function:
lua_getglobal(L, "tablename");      //[{}]
lua_pushcfunction(L, someFunc);     //[somefunc, {}]
lua_setfield(L, -2, "someFuncName");//[{somefuncName=somefunc}]
lua_pop(L, 1);                      //[]

When I first started writing lua C code it helped me to put in comments what
the
stack looks like after every command.  


Attachment: smime.p7s
Description: S/MIME cryptographic signature