lua-users home
lua-l archive

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


I need to read all of the data in a lua table (no array part) in C. I
know I can use `lua_next` to iterate the table :

int unpack_table_with_next(lua_State *L, int n) {
  int idx = lua_gettop(L);
  int s;
  lua_settop(L, idx + n * 2);
  lua_pushnil(L);
  s = 0;
  while (lua_next(L, idx) != 0) {
    lua_replace(L, idx + s * 2 + 2);
    lua_copy(L, -1, idx + s * 2 + 1);
   ++s;
  }
  lua_settop(L, idx + s * 2);
  return s;
}

This function can unpack the first n key-value pairs into the stack
and returns the number of actually unpacked.

I found if I can access the internal data structure of lua table, it
can run much faster.

int unpack_table(lua_State *L, int n) {
  int idx = lua_gettop(L);
  int s;
  lua_settop(L, idx + n * 2);
  const Table * t = (const Table *)lua_topointer(L, idx);
  int sz = sizenode(t);
  s = 0;
  StkId r = L->top - n * 2;
  for (i=0;i<sz && s<n;i++) {
     if (!isempty(gval(gnode(t, i)))) {
       Node *n = gnode(t, i);
       getnodekey(L, s2v(r++), n);
       setobj2s(L, r++, gval(n));
       ++s;
     }
   }
   lua_settop(L, idx + s * 2);
   return s;
}

It's 7x~8x faster.

I wish a similar C API can be introduced into a future version of lua.

-- 
http://blog.codingnow.com