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 unary # symbol is used to obtain the length of a string or table. The length operator returns the number of bytes for strings. The length operator returns the last numeric key whose value is not nil for tables starting from 1.
Tables are the only "container" type in Lua. They are associative arrays ([1]), which means they store a set of key/value pairs. In a Key/Value pair you can store a value under a key and then later retrieve the value using that key.
One possibility would be to count the number of elements, by using the metatable "newindex" key. When assigning something not nil , increment the counter (the counter could live in the metatable as well) and when assigning nil , decrement the counter. Testing for empty table would be to test the counter with 0.
The function you're looking for is unintuitive named lua_objlen
, or in Lua 5.2, lua_len
(there is a lua_rawlen
if 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 use lua_tolstring
to get the string and its length), so you should be familiar with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With