Reputation: 787
I'm still ramping up in lua, and I am not quite familiar with this syntax. What is happening when you pass in a function as a parameter like below?
Comm.setRouting(function(url)
for i = 1,4 do
local portIndex = "Path"..i
if url:match(portConfig[portIndex]) ~= nil then
return Comm.slots()[1], Comm.groups()[i]
end
end
end)
Upvotes: 2
Views: 219
Reputation: 911
The other answers are correct, but it might help you if you wrote your own function that calls another function:
function CallAFunction(func_to_call)
func_to_call()
end
You could pass a named function (an anonymous function assigned to a variable) or an anonymous function written on the fly.
function SayHello()
print("Hello!")
end
--[[
^This is equivalent to:
SayHello = function()
print("Hello!")
end
]]--
CallAFunction(SayHello)
CallAFunction(function()
print("Goodbye!")
end)
output:
Hello!
Goodbye!
and this can be done with parameters
function CallAFunction(func)
func("Bonjour")
end
CallAFunction(function(parameter)
print(parameter)
end)
Here, func
is the anonymous function, which accepts 1 parameter parameter
.
When you call func("Bonjour")
you are passing Bonjour as parameter
, like a normal function call.
Upvotes: 3
Reputation: 385
Here you're passing an argument to setRouting
that is an "anonymous function"
Functions are first-class values in Lua and can be stored in local variables, global variables and table fields. Here the function is being passed anonymously on the call stack to the setRouting
function.
setRouting
would be called a "higher-order function" because it accepts a function as its input.
The following page has some more information about functions in Lua:
https://www.lua.org/pil/6.html
Upvotes: 2
Reputation: 121649
A couple of things are happening in this example:
You're passing a function as a parameter. The callee (e.g. setRouting()
) can invoke that function. This is often referred to as a callback function.
You're defining the function itself, on-the-fly. This is an example of an "anonymous function", or a lambda function.
Upvotes: 1