lua-users home
lua-l archive

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


Thanks Rici, that did the trick.

Darius

----- Original Message ----- From: "Rici Lake" <lua@ricilake.net>
To: "Lua list" <lua@bazar2.conectiva.com.br>
Sent: Sunday, January 28, 2007 6:27 PM
Subject: Re: Creating a table through the API



On 28-Jan-07, at 11:57 AM, Darius Blaszijk wrote:

I'm trying to create a table equivalent to t = {1,2,3,4,5}

Sofar what I've come up with is:

 lua_newtable(L);
 lua_pushstring(L, PChar('1'));
 lua_pushnumber(L, 2);
 lua_settable(L, -3);
 lua_setglobal(L, PChar('t'));

It should create a table t = {2} but when I print the table contents it appears to be empty. Can anyone point me where I'm going wrong here?

You're confusing numbers with strings. That will create the table:
 t = {["1"] = 2}

What you want is something like this:

/*
   Given a vector of doubles, v, of length n, create a Lua
   array of numbers, leaving it on the top of the stack
 */
void table_from_array(lua_State *L, const double *v, int n) {
  int i;
  lua_newtable(L);
  for (i = 1; i <= n; i++) {
    lua_pushnumber(L, v[i-1]);
    lua_rawseti(L, -2, i);
  }
}

/* Test */
static const double sample[] = {
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};

table_from_array(L, sample, sizeof(sample)/sizeof(*sample));
lua_setglobal(L, "t");