Help: Purpose of Returning

Hello! I am completely new to scripting and I am having trouble understanding Returning. I have looked at a few Youtube videos but I don’t really understand what Returning is for or why it is used.

Can anybody give me a simple and clear definition/explanation for why Returning is used in scripting? Examples would be very useful.

(If this is in the wrong category please tell me, I haven’t used the Dev Forums for a couple of years.)

Thank you! :heartpulse:

2 Likes

Return is part of a function, so you can have a piece of code used multiple times across your script more easily. Here is a pretty simple example:

function Increment(number)
   number += 1 --add one onto the given number
   return number --give back the number
end

so this is a function, normally if you just call it like: Increment(1) then the function will run, but you wont get that number back. How you get the number back is like this:

local IncrementedNumber = Increment(1) --This will be 2

Since the function has a return, this variable will become what it returned. If there was no return at the end, then the function would return nil.
You can also use return to prematurely end a function at any point. Example of that:

function Above0(number)
   if number <= 0 then
       return false --By doing this, no code further down will run and the function ends here.
   end
   print("It was above 0!") --Because the code ends up there whenever the number was 0 or below, this will only print when it's above 0.
   return true --Same deal with this, this also returns true to whatever called this.
end
1 Like

There probably will be people who will give a quicker reply, but I’ll still give it a shot at trying to explain this in the simplest way possible.

Returning is used with something called functions. Functions are blocks of code that you can reuse multiple times. Example:

-- Below is a function which you can call anywhere in the script and as many times as you want.
function printHello()
    print("Hello world")
end

-- And this is where we call this function and the game will print "Hello world".
printHello()

Notice how the above example doesn’t use returning. Now, if you are going to perform the same math operation frequently, for example, you might want to create a function for it:

function sum(num1, num2)
   local sum = num1 + num2
   return sum
end

The above function sums num1 and num2, but we need a mechanism to get the result. Now, this is where Returning kicks in. By returning sum, we allow it to be processed by other parts of our code:

local returnValue = sum(5, 5) -- Storing the value that the function Returns.
print(returnValue) -- This will print 10.

Functions are arguably the most essential tool at developers’ disposal when writing code, and most functions return something, so you’ll encounter that very frequently. Make sure to embrace their power, and have fun!

3 Likes

Thank you! This helps a lot, the last section about prematurely ending the function confused me a little bit but your overall answer is very useful.

Thank you as well, I think I can better understand these now. :slight_smile:

this wouldn’t work, the two scripts down below should be better

function Increment(number)
   number += 1 --add one onto the given number
   return number --give back the number
end
function Increment(number)
   return number + 1 --give back the incremented number
end
4 Likes

https://education.roblox.com/en-us/resources/returning-values-from-functions

Thank me later.

2 Likes

He likely meant number += 1 in the the top function.

well that’s why I corrected them just incase

Return is part of Lua’s global environment of keywords. The replies in this thread so far do a decent job of explaining it, but I’ll elaborate some more.

In Lua, break and return statements (as well as continue, which has been added to Luau but does not exist in vanilla Lua) allow you to jump out from a code-block.

Functions in Lua end with return by default, so if you do not need to receive any kind of value from your function, do not write a return statement. For Lua syntax, return can only exist as the last statement of a specific block. It would replace break statements in functions that actually need to see information provided (IE, if you need information, use return, if you only need to end code chunk, use break – this is why break is used in loops even though you could syntactically use return as well).

Here is a very basic example of return:

function GiveBack(Value)
   return Value
end

print(GiveBack "Example") -- "Example"

Let’s ignore the fact that the above code is pointless. You’ve wrote a callable function GiveBack. This function will implicitly return, because functions do that naturally. However, you want to get back the value that you pass to the function. So you write a return statement, and want your caller to receive it. In this case, the caller is our print statement.

What’s nice about Lua is how return acts in response to its syntax. You can return as much information as you’d like to.

Here’s another example. Pretend you were writing a function to decide what 25% and 75% of a passed number value were. Of course this function would only be useful if you could receive your result from it, and so you would need to return both values.

BaseNumber = 20

function GetPercents(Value)
  return Value * .25, Value * .75
end

local Percent1, Percent2 = GetPercents(BaseNumber)

print("25% of BaseNumber is "..tostring(Percent1))
print("75% of BaseNumber is "..tostring(Percent2))

First we write a variable to represent some number we want to obtain the percentages of, followed by a function that calculates and returns those values. In Lua, you can catch and pass multiple values at once. We catch both results (because mathematical calculations are done inside the function we can assume results to always be number types) and assign them to variables. Then we can use those results at our higher scope, even though they were calculated in the function.

3 Likes

Yeah. There are three main uses of return two have already been said. But the last use of return is in ModuleScripts.

If you have used JS then return would function similarly to export. We use return in a ModuleScript to say what the script will be what is stored in the variable when the ModuleScript is required

-- ModuleScript
return "Hey"
-- Script
local Module = require(script.ModuleScript)
print(Module) -- Hey

Most of the time what is returned is either a function or a table/dictionary.

-- ModuleScript
local Module = {}
Module.Information = "TEST_INFO"
return Module
-- Script
local Module = require(script.ModuleScript)
print(Module.Information) -- TEST_INFO
-- ModuleScript
function GoodMorning(name)
    print(name..". Good morning!")
end
return GoodMorning
-- Script
local GM = require(script.ModuleScript)
GM("Bob") -- Bob. Good morning!

ModuleScripts are used in created Modules(Classes and OOP) which is basically code that you are going to be reusing a lot or different scripts.

1 Like

To further elaborate on this, Luau modules are what’s referred to as a package. Modules build a new code environment (aside from Global env) to avoid name collisions across differing libraries.

Being source containers as they are, return use in modules is actually no different functionally than it is anywhere else. Involved code runs a single time per Lua environment & suspends requiring thread until a return is received. It runs top-level once and utilizes return the same way that return is utilized everywhere else.

My point simply being that understanding return at a fundamental level will enable you to understand its usage in all cases.

1 Like

I can also be used to break out of a nested loop:

for a = 1, 10 do
  for b = 1, 10 do
    print("Break")
    break
  end
end

for a = 1, 10 do
  for b = 1, 10 do
    print("Looped")
    return
  end
end

Output:

Break
Break
Break
Break
Break
Break
Break
Break
Break
Break
Looped

Keep in mind that return will stop all code from running after it within the scope it’s returning from.

1 Like

Here’s an example:

local objectname = function(object)
      return object.Name
end
----
print(objectname(game.Workspace.Part)) -- prints "ItsAPart"

(People have probably covered this before me but why not give it a shot)

Returning is a keyword in Luau used to, you guessed it return numbers.

local function getName() -- A function is made
local obj = workspace.Part -- Part is referenced
return obj.ClassName -- The part's class name is returned
end
print(getName()) -- Prints the class name.

Basically, it helps you access a certain value by calling a function(probably not the best explanation).