lua-users home
lua-l archive

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

2013/9/23 Andrew Starks <>:
> I have many setter methods that handle properties that represent an
> inventory of one or more objects of the same class (to borrow from
> OOP).
> So that I don't need to write a "set_prop" and "set_props" function, I
> write this quite a bit:
> local function f(arg, ...)
>     if (...) then
>         return arg, f(...)
>     else
>         return arg
>     end
> end

I assume something non-trivial is being done too, i.e

local function f(arg, ...)
    if (...) then
        return arg, f(...)
        arg = complicated_function_of(arg)
        return arg
    end end

So you seem to be using recursion only for the sake of
being able to return a vararg list. If you need to stick to
interpreted Lua, you can do that with coroutines, but it is
easier IMHO to write an API function for this case.

Such a function is included in the `xtable` module that
John Hind and I wrote:

That module itself has not proved to be popular, but you might
want to extract just 'map'. All it does is to return a variable-length
list of a function or table lookup applied to all the elements of the
vararg list.

/*,table_or_monadic_function,...) */
static void tuple_call(lua_State *L) {
  int i, top=lua_gettop(L);
  for (i=2; i<=top; i++) {
    lua_pushvalue(L,1); lua_pushvalue(L,i); lua_call(L,1,1);
static void tuple_index(lua_State *L) {
  int i, top=lua_gettop(L);
  for (i=2; i<=top; i++) {
    lua_pushvalue(L,i); lua_gettable(L,1);
static int tuple_map(lua_State *L) {
  if (lua_type(L,1)==LUA_TFUNCTION) tuple_call(L);
  else if  (lua_type(L,1)==LUA_TTABLE) tuple_index(L);
  else return 0;
  return lua_gettop(L)-1;