lua-users home
lua-l archive

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


Roberto wrote:
 I'd like to see a generator in the library for lists that doesn't
 include the index as ipairs does:

   for v in list(t) do ... end

Such generator would have to keep its own state, and so would be more
expensive than `ipairs'...

I'm a curious guy so I decided to test out your theory. In my simple timing tests I couldn't see a significant performance difference between ipairs and a list generator I implemented (below).

While doing this excercise, I ran into a few other issues:

* use of var_1 in for loop

  The passing of var_1 to the generator function in the for loop seems
  arbitrary.  Indeed, I didn't need it in the list implementation, and
  could likewise picture situations where more than var_1 are
  needed.  Why not just rely on closures?

  Even passing the table to the generator seems dubious, as a
  generator may simply synthesize a sequence of numbers, for example,
  and not require a table at all.


* use of rawgeti in table generators

  Use of raw accessors precludes array and list proxies.


-John


----

static int list (lua_State *L) {
  lua_Number i = lua_tonumber(L, lua_upvalueindex(1));
  luaL_check_type(L, 1, LUA_TTABLE);
  i++;  /* next value */
  lua_pushnumber(L, i);
  lua_replace(L, lua_upvalueindex(1));
  lua_rawgeti(L, 1, (int)i);
  return 1;
}

static int luaB_list (lua_State *L) {
  luaL_check_type(L, 1, LUA_TTABLE);
  lua_pushnumber(L, 0);  /* initial value */
  lua_pushcclosure(L, list, 1);  /* return generator */
  lua_pushvalue(L, 1);  /* and state */
  return 2;
}



--
http:// i      .   /