What does Return do?

Hey there!

So iv’e been digging on the Dev Forum aswell as the DevHub to try and understand how returning works. Unfortunately, i can’t seem to find out.

In my case, i’m trying to return two values from a function inside a module script into a local script. How would i do this? Would you also mind explaining how returning works?

Any help is appreciated.

3 Likes

Return basically gives you something in return when firing a function. :wink:

function GimmeSomethingToPrint()
	return "IsThisGoodEnough?"
end

print(GimmeSomethingToPrint)

There’s more to it, though. Return also stops the function and will not continue to the next lines of code - which is a good thing to keep in mind if you want to stop a function with ease if it doesn’t meet your conditions (e.g. if an object doesn’t exist and :FindFirstChild() returns nil).


This is also very commonly used by modules by default. If you create a new module, then the default module set up would look somewhat like this:

local Module = {}

return Module

The table {} is exactly what you get when you require() a module like this in a script.

7 Likes

return allows you to send back variables/arguments that are created from a function to be used outside of it.

For example:

function Add(a,b)
    local result = a+b
    return result
end

local c = Add(5,2) -- variable 'c' can be anything
print(c) -- 7

Also, returning multiple variables is easy! Just add a comma for each variable that you want to return and define:

function HokeyPokey(a,b)
    local result1 = a+b
    local result2 = a-b
    return result1,result2
end

local added,subtracted = HokeyPokey(9,4)
print(added,subtracted) -- 13 5

If you want to omit a returned value from a function:

function HokeyPokey(a,b)
    local result1 = a+b
    local result2 = a-b
    return result1,result2
end

local _,subtracted = HokeyPokey(9,4)
print(subtracted) -- 5

Hope this helped!

4 Likes

return allows you exit from a function and send back data if necessary

2 Likes

How would i be able to return two separate string variables back modified in one function?

1 Like
local function someFunction()
    local String1 = "Hello"
    local String2 = "World"

    return String1, String2
end

local String1, String2 = someFunction()

print(String1, String2)

2 Likes

What if String1 and String2 have already been defined before the function? Would i just do

String1, String2 = someFunction(AlreadyDefinedVar,AlreadyDefinedVar2)

Or would i do

AlreadyDefinedVar = String1
AlreadyDefinedVar2 = String2
1 Like

if you want to update String1 and 2 just do this:

String1, String2 = someFunction(String1,String2)
2 Likes