lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


RJP Computing wrote:
How do I iterate thru the keys of a table using the C API? More
specifically, I don't want to know the keys or values of a table. I just
want to iterate through them and find out there "names".

Define `names'. You mean string keys? Those are still keys :). Anyways, what you're looking for is lua_next(). It's entry in the manual includes an example:

     /* table is in the stack at index 't' */
     lua_pushnil(L);  /* first key */
     while (lua_next(L, t) != 0) {
       /* uses 'key' (at index -2) and 'value' (at index -1) */
       printf("%s - %s\n",
              lua_typename(L, lua_type(L, -2)),
              lua_typename(L, lua_type(L, -1)));
       /* removes 'value'; keeps 'key' for next iteration */
       lua_pop(L, 1);
     }

Which you can find at http://www.lua.org/manual/5.1/manual.html#lua_next .
Note that you can't iterate over keys or values exclusively; they come in pairs. But of course you can just ignore the values if you're not interested in them. Do make sure to pop() both at the end of each iteration.

Good luck,

 - Peter Odding