lua-users home
lua-l archive

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


> this is a newbie question, bu I'm haviong trouble passing in 
> a 2d table from 
> lua, into c and extracting the results.  I have a vectors of 
> tables that I'm 
> trying to iterate over,  but right before I read in the 
> second value of the 
> first table (2), the program crashes.  What am I doing wrong?

Trivially: Are you sure all your tuples are of size 3? you pass a static
array to fillTuple() which is filled and could overflow and cause a crash?

I think you need to pop your first table off the stack before accessing the
second (see below). I havent tested this :-)

If you get stuck with the Lua C API, a really useful utility is lua2c. Its
really easy to forget to pop stuff off the stack or get the order wrong when
manipulating Lua via C.

lua2c can be found via http://lua-users.org/wiki/LuaAddons

Regards,
Nick


> On the Lua side:
> 
> 	table = { {1,2,3}, {4,5,6}, ... , {123, 456, 789} }
> 
> 	function(table)
> 
> On the C side:
> 
> 	void fillTuple(lua_State *L, int i, double *array)
> 	{
> 	   int     size = lua_getn(L,i);
> 	   int     k = 0;
> 
> 	   if (size > 0)
> 	   {
> 	      for (k = 1; k <= size; k++)
> 	      {
> 	         lua_rawgeti(L, i, k);
> 	         array[k - 1] = lua_tonumber(L, -1);
> 	      }
> 	   }
> 	}
> 
> 	void fillList(lua_State *L, int i, list_t **list, int *n)
> 	{
> 	   int     k = 0;
> 	   int     size = lua_getn(L,i);
> 	   double  array[3];
> 
> 	   if (size > 0)
> 	   {
> 	      *n = size;
> 	      *list = (list_t*) malloc(*n * sizeof(list_t));
> 
> 	      for (k = 1; k <= *n; k++)
> 	      {
> 	         lua_rawgeti(L, i, k);     // get table[k]
> 		  fillTuple(L, -1, array); // read table[k]

               lua_pop(L,1);   // we dont need table[k] now
> 
> 	         (*list)[k - 1] = makeItem(array);
> 	      }
> 	   }
> 	}