• Subject: Re: Filling multiple tables in one loop
• From: Choonster TheMage <choonster.2010@...>
• Date: Sat, 18 May 2013 20:05:40 +1000

```On 18 May 2013 19:50, Bas Groothedde <lua@xoru.net> wrote:
> Hey List,
>
> I've got a C function in which I want to fill two tables and return them
> both as result,
> however I'm a little stuck on the logic behind it. Here's some example code,
> but it
> only generates one table.
>
> int multipleTables(lua_State *L) {
>     int min = luaL_checkint(L, 1);
>     int max = luaL_checkint(L, 2);
>
>     // I want to fill two result tables in one loop
>     lua_newtable(L);
>     for(int i = 0; i < (DATA_SIZE - 1); i++) {
>         lua_pushnumber(L, i + 1);
>         lua_pushnumber(L, data[i]);
>         lua_settable(L, -3);
>
>         // if data[i] > min and < max, I want to add it to a second result
> table
>         if(data[i] > min && data[i] < max) {
>             // push to second result table
>         }
>     }
>
>     return 2;
> }
>
> How would I fill a second result table in that same loop? Looping through
> the data
> twice would be too slow, considering 'data' may have 10000 elements.
>
>
>
> Cheers
>
> --
> ________________________________
>
> Bas Groothedde
> Imagine Programming

Try this code:

int multipleTables(lua_State *L) {
int min = luaL_checkint(L, 1);
int max = luaL_checkint(L, 2);

lua_createtable(L, DATA_SIZE - 2, 0); // Create the first table
that holds every element from `data` and pre-allocate space for
(DATA_SIZE - 2) array elements.
lua_newtable(L); // Create the second table to hold the elements
that fall between min and max, don't pre-allocate any space.
for(int i = 0; i < (DATA_SIZE - 1); i++) {
lua_pushnumber(L, data[i]); // Push the data element
lua_rawseti(L, -3, i + 1); // firstTable[i+1] = data[i]

// if data[i] > min and < max, I want to add it to a second result table
if(data[i] > min && data[i] < max) {
lua_pushnumber(L, data[i]); // Push the data element
lua_rawseti(L, -2, i+1); // secondTable[i+1] = data[i]
}
}

return 2;
}

```