lua-users home
lua-l archive

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


Hi,

I have a simple problem using Lua 5 which I hope someone can help me with.

I want to call a C function that allocates an object, and then returns a
table with the object ptr and some methods that can be called on that
object...

e.g.

In Lua script...

	MyThing = ObjectFactory.CreateThing()
	MyThing.DoSomething()


The C(++) code looks something like this (Some details have been
omitted)....

// Add a thunked object and function pointer to a table
#define addmemberobjthunk(L, N, THUNK, OBJ, FN, IDX)	\
							\
	lua_pushstring(L, N);				\
	lua_pushlightuserdata(L, (void*)FN);		\
 	lua_pushlightuserdata(L, (void*)OBJ);		\
	lua_pushcclosure(L, THUNK, 2);			\
	lua_settable(L, IDX);

// Add an object pointer to a table
#define addmemberdata(L, N, DATA, IDX)		\
						\
	lua_pushstring(L, N);			\
	lua_pushlightuserdata(L, (void*)DATA);	\
	lua_settable(L, IDX);

// This function called via thunk...

void ObjectFactory::CreateThing(lua_state* L)
{
	Thing* pThing = new Thing();

	// Create table and push onto stack
	lua_newtable(L);

	// Get index of table on stack
	int index = lua_gettop(L);

	// Add function to table
	addmemberobjthunk(L, "DoSomething", MyThunker, pThing, pDoThingFn,
index);

	// Add object ptr into table as 'id'
	addmemberdata(L, "id", pThing, index);

	// Table is be returned back to Lua
}



.... but I get an error... "attempt to index global 'MyThing' (a nil value)

What am I doing wrong?

Many thanks,

Will