lua-users home
lua-l archive

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


On 11/30/2017 02:37 PM, Dirk Laurie wrote:
> Does a patch that allows the clumsy idiom
> 
>     function(a,b,c)
>       a = a or 0
>       c = c or 1
> 
> to be replaced by
> 
>     function(a=0,b,c=1)
> 
> already exist?
> 

Well, if I was frustrated I'd try to write wrapper function for such things:

local wrap =
  function(f, defaults)
    -- assert_function(f)
    -- assert_table(defaults)

    local result =
      function(...)
        local args = table.pack(...)
        local n = math.max(args.n, defaults.n)
        for i = 1, n do
          args[i] = args[i] or defaults[i]
        end
        return f(table.unpack(args, 1, n))
      end

    return result
  end


local core =
  function(a, b, c)
    print(a, b, c)
  end

local wrapped_core = wrap(core, {0, nil, 1, n = 3})

wrapped_core()

-- Martin