I have a c function that is called from lua. The first parameter is a table. That table is abused as an input array of numbers to an underlying api. So right now my code looks like this:
int n = 0;
lua_pushnil ( L );
while ( lua_next ( L, 2 ) ) {
n++;
lua_pop ( L, 1 );
}
int *flat = alloca ( n * 4 );
lua_pushnil ( L );
int i = 0;
while ( lua_next(L,2) ) {
flat[i++] = (int)lua_tonumber( L, -1 );
lua_pop ( L, 1 );
}
I typed the code blind, so please forgive errors. Also no error checking. But the problem is that I have to do the while loop twice. Is there an easy way to avoid that? I want to optimize for the case where the input is good – a table of ints.
The function you’re looking for is unintuitively named
lua_objlen, or in Lua 5.2,lua_len(there is alua_rawlenif you wish to avoid metamethod invocations). It serves many roles (though some, like the length of a string, aren’t very useful when you can just uselua_tolstringto get the string and its length), so you should be familiar with it.