lua-users home
lua-l archive

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

On Tuesday, September 24, 2013, Dirk Laurie wrote:
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

Not really and it wouldn't be the first time I've labored under an ignorance that others shed in chapter 1 of PiL. :P This example might be better:

function f:add_one_or_more_props(args,...)
--do stuff to add props 

if (...) then
  return self

Or another variant: 

function f:add_one_or_more_props(args,...)
  if not args then return self end
  --do stuff

I think that it's a much simpler question than I communicated and the second version might be my answer, although erroring on the first call, if it doesn't contain arguments, is not possible...


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;