【问题标题】:Lua - Passing a function with some arguments already filledLua - 传递一个已经填充了一些参数的函数
【发布时间】:2020-02-04 17:43:44
【问题描述】:

我想传递一个函数作为参数,传递的函数有两个参数。我想填充第一个参数,但第二个未填充。示例如下:

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.")

对函数的期望调用:

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

执行的期望输出:

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.

我该怎么做?

【问题讨论】:

  • 为什么不将 2 个值传递给 b,例如 b(a, "first call"),而您将 b 定义为 function b(givenfunction, arg1) givenfunction(arg1, "the second argument.") end
  • 因为 b 是我们无法修改的函数。所以我们想传递一个函数 a(我们自己写的),它可以有一个不直接传递给 b 的参数。

标签: function lua arguments


【解决方案1】:
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"))

【讨论】:

  • 工作就像一个魅力。谢谢! :)
猜你喜欢
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多