lua-users home
lua-l archive

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


On Thu, Sep 01, 2005 at 09:19:42AM -0700, Mark Hamburg wrote:

> I've been contemplating whether Lua needs:
> 
>     function argforeach( fn, ... )
>         for I = 1, select( "#", ... ) do
>             fn( ( select( I, ... ) ) )
>         end
>     end
> 
> This should be written in C to avoid the performance issues cited above and
> probably needs a better name.

This is very similar to Lisp's mapcar and Python's map functions.  My
particular implementation (mapped to the global _G.maplist):

    int utilsL_maplist( lua_State* L )
    {
      int nargs = lua_gettop(L);
      int i;

      luaL_checkstack(L,2*nargs+2, "cannot allocate space for return list");

      if (! lua_isfunction(L,1))
        luaL_typerror(L, 1, "function");

      for (i=2; i <= nargs; ++i) {
        lua_pushvalue(L,1);
        lua_pushvalue(L,i);
        lua_call(L,1,1);
      }

      return nargs-1;
    }

-- 
Shannon Stewman         | Let us walk through the waning night,
Caught in a whirlpool,  | As dawn-rays tickle our toes, the dew soothes
A quartering act:       | Our blistered soles, and damp bones stir
Solitude or society?    | As crimson cracks under the blue-grey sky.