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-----
[] On Behalf Of Dolphin
Sent: 11 March 2009 15:28
Subject: Re: Unable to access table using lua after creation of table in C

I would suggest looking at (The Stack).
of the lua C API operates on values on the stack.  I use
as a reference when I need to remember what the functions do.  Stack
takes a bit of getting used to, and some of the lua C api may do thinks you
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
stack looks like after every command.  

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