Can anyone explain return functions?

Can anyone help explain to me return functions during parameters and what would happen if you dont use it i just cant understand it :sob: .

Hello there.
What do you mean by ‘return functions during parameters’? I don’t understand what you’re requesting to be explained.
Do you mean, perhaps, that what does the keyword return do within a function?
To make it even clearer what you’re referring to, you may post an instance of what you want explained here, such as a block of code containing what you don’t understand.

1 Like

well if OP does mean return, basically it can send back info to where the function was originally called. for example (sorry for formatting I am unable to indent on dev forum):

You could calculate a variable with a function like this

local function example(a)
local b = a*2
return b
end

local variable = example(2)
--Variable will be equal to 4 in this context

--you could also use it directly instead of creating a variable with it
if example(2) == 4 then
print("It works!")
end
3 Likes

Indeed, Freddd7878 , thanks for contributing.

About indentation

As a cultural contribution, I indent here by using simple spaces… Your code would look something like this with two spaces as indentation (Studio uses more by default, though):

local function example(a)
  local b = a*2
  return b
end

local variable = example(2)
--Variable will be equal to 4 in this context

--you could also use it directly instead of creating a variable with it
if example(2) == 4 then
  print("It works!")
end

Hope this indentation tip helps.


1 Like

Functions and return.

Functions allow programmers to package code for later execution. Arguments & parameters are a component of functions that allow us to set placeholders within that packaged code. These placeholders can be filled at runtime when the function is called. For example:

local function add(numberA: number, numberB: number): number
    print(numberA + numberB)
end

numberA and numberB are undefined values. However, we define how they should be used within the code. When add is called, these values will be replaced by the ones given to the function:

add(2, 8) --> 10

-- Equated to print(2 + 8)

When you call a function, the program needs to jump to the code we wrote within that function. You can imagine it as:

local function add(numberA: number, numberB: number): number
    print(numberA + numberB)
end

add(2, 8) -- We're here...
local function add(numberA: number, numberB: number): number
    print(numberA + numberB)  -- Now we're here...
end

add(2, 8)

The program needs to come back to where add was called to continue its natural flow. This happens at the end of the function, or when the programmer uses the “return” keyword" .

local function add(numberA: number, numberB: number): number
    print(numberA + numberB) 
end

add(2, 8) -- We're back here, but there's nothing left to do
-- Continuing on...

Programmers package code for a couple reasons, but the foremost reason is for code re-usability. Functions will often create data, and we want to share that data with the rest of the program. return also provides programmers with the opportunity to export that data:

local function getPlayersWhoseUsernameContains(word: string): {Player}
    local players = {}

    for _, player in Players:GetPlayers() do
        if string.find(player.Name, word) then
            table.insert(players, player)
        end
    end

    return players
end

Now instead of writing this loop every time where I need an array of players whose username contains a certain word, I can call upon the above function:

local players = getPlayersWhoseUsernameContains("Apple")

Just as execution returns to where the function was called, so does the table I created. This effectively assigns the “players” variable to the result of the work done in the function. If you’ve worked with the Roblox Studio API for some time, you would have already seen this in action—you see it almost everywhere, in fact. Here’s an example:

local child = instance:FindFirstChild("Child")

return doesn’t have to be used at the bottom of a function, though. It can be used at any point within it. As I said earlier, with return, programmers can force program execution to return to the function call-site. This gives us the ability to end functions early:

local function serverContainsPlayerNamed(name: string): boolean?
    for _, player in Players:GetPlayers() do
        if player.Name == name then
            -- Stop iterating, end the function, and give back true.
            return true
        end
    end

    -- The function was allowed to reach this point. No player found. Give back false.
    return false
end

Higher-order functions

If all that was already known to you, then you may be asking about HOFs. Higher-order functions are functions that accept functions and/or return them. We can treat functions as any other return value or parameter as Lua(u)'s functions are first-class functions. Functions that are passed as arguments to others are dubbed “callbacks”. The execution of callbacks are typically delegated to the higher-order function they were passed to. In this event, HOFs typically use the given function in a certain way, like providing a specific set of arguments:

local function callWithHelloWorld(callback: () -> string)
    callback("Hello, world!")
end

callWithHelloWorld(print) --> Hello, world!

Some examples of HOFs that you may have encountered are pcall and RBXScriptSignal:Connect (the “Connect” method of events).

An example of an HOF that returns functions:

local function callsWith(callback: (any) -> (), value: any): () -> ()
    return function()
        callback(value)
    end
end


local helloWorld = callsWith(print, "Hello, world!")

helloWorld() --> Hello, world!
helloWorld() --> Hello, world!
helloWorld() --> Hello, world!

This type of HOF is typically dubbed a factory. Some examples of this you may have encountered are pairs and ipairs.

2 Likes

Just think of them as math functions like sin, cos, tan. You’d input a number into these functions and they’d give/return a number/output

3 Likes