lua-users home
lua-l archive

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


On Sat, Jul 14, 2007 at 06:19:10PM -0700, Chintan Gandhi wrote:
> How do I push an int array to the stack from C and how do I retrieve it 
> from within Lua?

An array is just a table with numeric keys, so first create it
on top of the stack:

  lua_newtable(L);

Then for example to store the string "foo" as element 7 of the
array:

  /* Put a single object you want to store in the array. */
  lua_pushstring(L,"foo");

  /* The stack currently has the string in the top slot, and the
   * table itself in the next slot down (-2).  This pops the
   * the top object and stores it into the table with the key 7.
   */
  lua_rawseti(L,-2,7);

Once the array is filled, you'll need to figure out how you want to
make it visible in the Lua script.  Probably the easiest thing
is just returning it directly to whatever Lua code called your
C function.  To do this make sure the table is on top of the stack
and then use:

  return 1;  /* return one object back to Lua */

>From within Lua, you'd then have something like:

  myarray = mycfunction()

See Programming in Lua for more information about handling arrays from
C, for example:

  http://www.lua.org/pil/27.1.html

That version of the book is aimed at Lua 5.0.  Note that Lua 5.1 has
some differnces in the language itself when it comes to handling
array-style tables, such as the new "#" operator.  There is a 2nd
edition of the book for sale which covers 5.1.

                                                  -Dave Dodge