lua-users home
lua-l archive

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


> That is, for a table of key/value pairs, give me the key (or value,
> ideally), of the 'nth' item in the table....
>
> Kinda strange this isn't available, IMHO.

The main problem here, AFAICT, is that non-numeric keys aren't ordered in any 
useful way. The "nth" item may or may not be the "nth" item any more, if the 
table is changed in any way:

Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
> t = { a = 1, b = 2, c = 3, d = 4 }
> for k,v in pairs(t) do print(k, v) end
a       1
c       3
b       2
d       4
> t.e = 5
> for k,v in pairs(t) do print(k, v) end
a       1
c       3
b       2
e       5
d       4

Since there's no useful reason to access a key/value pair by its absolute 
position in the table, a function isn't provided for it. If you do need it 
for some odd reason, the best way would probably be to use lua_next. Probably 
not the most efficient way to do it, but you get what you code for. (if you 
need better, check out structs Table and Node in lobject.h, and the code in 
table.c).

/* expects a table to be at stack position -1 */
/* counts from 0 */
/* doesn't check for table size */
void getkeyatn(lua_State* L, int n)
{
    lua_pushnil(L);
    while(--n)
    {
        lua_next(L, -2);
        lua_pop(L, 1);
    }
}