Alexandre Willame
Alexandre Willame

Reputation: 455

Lua - Passing a function with some arguments already filled

I want to pass a function as an argument, the function to pass takes two arguments. I want the first argument filled, but the second one unfilled. Here is the example:

function a(firstarg, secondarg)
    print ("this is the" .. firstarg .. "to the a function and the b function gave it ".. secondarg)
end

function b(givenfunction)
    givenfunction("the second argument.")

The desired calls to the function:

b(a("first call"))
b(a("second call"))

The Desired output of the execution:

this is the first call to the a function and the b function gave it the second argument. 
this is the second call to the a function and the b function gave it the second argument.

How can I do that?

Upvotes: 0

Views: 206

Answers (1)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23727

function inner(firstarg, secondarg)
   print ("this is the" .. firstarg .. "to the a function and the b function gave it ".. secondarg)
end

function a(firstarg)
   return function (secondarg) 
      return inner(firstarg, secondarg)
   end
end

function b(givenfunction)
   givenfunction("the second argument.")
end

b(a("first call"))
b(a("second call"))

Upvotes: 3

Related Questions