[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Creating a table through the API
- From: Rici Lake <lua@...>
- Date: Sun, 28 Jan 2007 12:27:34 -0500
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");