lua-users home
lua-l archive

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


> In Lua 5 getn is no longer in the C API but it is available as
table.getn in
> the base lib: (sample code w/o checking of any kind :-)
> 
> /* get "table" table */
> lua_pushstring(L, "table");
> lua_gettable(L, LUA_GLOBALSINDEX);
> 
> /* get "getn" entry */
> lua_pushstring(L, "getn");
> lua_gettable(L, -2);
> 
> /* call it and get result */
> lua_pushvalue(L, index);  /* index of your table in the stack */
> lua_call(L, 1, 1);
> n_elements = lua_tonumber(L, -1);  /* store table size */
> lua_pop(L, 1);  /* pop table size */

But assuming getn gets called just once as in my case and setn hasn't
been used, what getn will do is this:

    n = 0;
    for (;;) {
      lua_rawgeti(L, t, ++n);
      if (lua_isnil(L, -1)) break;
      lua_pop(L, 1);
    }
    lua_pop(L, 1);

While wether this is cheap or expensive denpends on how it's used it
is almost exactly what I have to do to actually copy the table. I just
have to add table[n] = lua_tonumber(L, -1) before the inner lua_pop
call. That's whats bugging me mostly. I don't want to do the job twice
when I theoretically could have copied the table during the first
iteration. So I was hoping that there would be some sort of trick to
do it.If there isn't I'll have to do it this way I guess.