Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the table length of a lua table in c?

Tags:

lua

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.

like image 278
starmole Avatar asked Sep 27 '12 08:09

starmole


People also ask

How do you find the length of a Lua table?

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.

What is a table value Lua?

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.

How do I know if a table is empty Lua?

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.


1 Answers

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.

like image 79
Nicol Bolas Avatar answered Nov 03 '22 12:11

Nicol Bolas