lua-users home
lua-l archive

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


On Tue, 19 Aug 2014 15:38:58 +0200
Jan Behrens <jbe-lua-l@public-software-group.org> wrote:

> extending ipairs in such way to accept functions (and possibly creating
> an easy to use API interface for ordinal iteration on functions AND
> tables) would encourage library programmers to create interfaces that
> do not distinguish between (function) iterators and (table) sequences.

With an API interface, I mean something like this:

#define luaL_geti(L, idx, i) ( \
        (*(i))++, \
        lua_type((L), (idx)) == LUA_TFUNCTION \
        ? (lua_pushvalue((L), (idx)), lua_call((L), 0, 1)) \
        : (lua_rawgeti((L), (idx), *(i))), \
        lua_isnil((L), -1) \
        ? (lua_pop((L), 1), LUA_TNIL) \
        : lua_type((L), -1) \
        )

(This is just a draft. A real implementation might want to check
types for safety and/or respect the __call metamethod.)

This would allow something like:

> function printcsv(seq)
>   for i, v in ipairs(seq) do
>     if i > 1 then io.stdout:write(",") end
>     io.stdout:write(v)
>   end
>   io.stdout:write("\n")
> end

also in the C world:

static int printcsv(lua_State *L) {
  int i;
  luaL_checkany(L, 1);
  for (i=0; luaL_geti(L, 1, &i); lua_pop(L, 1)) {
    if (i > 1) fputs(",", stdout);
    fputs(lua_tostring(L, -1), stdout);
  }
  fputs("\n", stdout);
  return 0;
}

The resulting printcsv functions (both the Lua and the C variant) would
then accept either (function) iterators or (table) sequences. It
wouldn't matter for the caller.


Regards
Jan