Warm tip: This article is reproduced from stackoverflow.com, please click
arguments function lua

Passing a function with some arguments already filled

发布于 2020-04-19 09:18:41

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?

Questioner
Alexandre Willame
Viewed
65
Egor Skriptunoff 2020-02-05 02:04
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"))