lua-users home
lua-l archive

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



Alternatively.

If your array is huuuuge and you want to spare the C->Lua conversion, you can keep (a copy of it) as a C array, and just push a userdata with '__index' metamethod enabled. And maybe '__gc'.

I've used this succesfully for SDL_mixer callbacks, where music samples are passed in real time. I'll be glad to provide the code as a personal email (it's also part of gluax.c).

-asko


Dave Dodge kirjoitti 15.7.2007 kello 5:05:

On Sat, Jul 14, 2007 at 09:54:30PM -0400, Dave Dodge wrote:
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?

Sorry, just noticed the "int array" aspect of this.  Let's assume you
have an array "arr" containing 10 integers in C.  To create a copy of
this array on top of the Lua stack:

  lua_newtable(L);
  for(int i = 0;i < 10;i++)
  {
    lua_pushinteger(L,arr[i]);
    lua_rawseti(L,-2,i + 1);
  }

Note that on the Lua side arrays are normally numbered starting with
1, so I used (i + 1) to renumber your array elements from 0..9 to
1..10.  If for some reason you need the array numbered 0..9 in Lua you
can do that, but be warned that if you use any of Lua's special
operators or functions for handling array-style tables, they're still
going to assume the array starts at 1 and might get confused.

                                                   -Dave Dodge