Kelson Ball
Kelson Ball

Reputation: 983

Lua variable length function arguments are nil

I am trying to write a curry function in lua 5.2. My code looks like this:

function add(a, b)
    return a + b
end

function curry(func, value)
    return (function (...)
        return func(value, table.unpack(arg))
    end)
end

add2 = curry(add, 2)

print(add2(3))

The parameter arg however does not contain the value passed into the add2 function.

When I try and run the example from the Lua documentation it errors because arg is nil.

printResult = ""

function print (...)
  for i,v in ipairs(arg) do -- arg is nil
    printResult = printResult .. tostring(v) .. "\t"
  end
  printResult = printResult .. "\n"
end

How can I use variable length functions in 5.2 if this is not working?

Edit:

As user @siffiejoe has pointed out, my function here is just doing partial application, not proper currying. Here is my implementation of a proper curry function in lua using the error fix from the accepted answer.

function curry(func, params)        
    return (function (...)
        local args = params or {}        
        if #args + #{...} == debug.getinfo(func).nparams then
            local args = {table.unpack(args)}
            for _,v in ipairs({...}) do
                table.insert(args, v)
            end
            return func(table.unpack(args))
        else
            local args = {table.unpack(args)}
            for _,v in ipairs({...}) do
                table.insert(args, v)
            end
            return curry(func, args)
        end
    end)
end

Feel free to suggest changes and add test cases here

Upvotes: 2

Views: 3839

Answers (1)

Tom Blodget
Tom Blodget

Reputation: 20812

Since Lua 5.1, arg in this context has been replaced by ... (except that the latter is a list instead of a table).

So, table.unpack(arg) should be just ....

See Breaking Changes. The Lua Reference manuals are very good and this section in particular is highly useful.

Upvotes: 11

Related Questions