Search code examples
lua

What is happening when you have a function as a parameter?


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)

Solution

  • 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