Can somebody please explain what "return" does?

Sorry for asking such a dumb question, I’m just starting out as a programmer in Lua. I don’t understand anybody’s explanation. Hopefully, I can find help here.

2 Likes

i mean ig the question im trying to ask is really why i would need to use this

1 Like

Returning is actually pretty straight forward. Here are a few examples:

function exampleReturn()
     return "This is the example!"
end

What this code does is it returns the value, that value being “This is an example!”.

We can then see this in action by doing this:

local returnedVal = exampleReturn()
print(returnedVal)

You may be wondering, why print the function? Well it doesn’t actually print the function itself, it prints the value it returned from that function.

Another example:

function multiply(x, y)
 return x*y
end

local returnedValue = multiply(5, 4)
print(returnedValue)

OUTPUT: 20

You can read more about returning here:

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

Hope this helps!

4 Likes

what a legend :smiley: this helped me a lot

3 Likes

When you call a function, like:

local function BakeACake(Type)
     --code run to bake the cake of that type
end

You call the function with a line like this:

BakeACake("Chocolate")

That is “one-sided” meaning you send the request for the function out, and then move on. You can also run a function like this:

a = BakeACake("Chocolate")

In that scenario you are assigning the variable “a” to the return value of “BakeACake()”
Remember though, that in that function, you only ran code to bake the cake, nothing else.
To make the function return something, include the return line.

local function BakeACake(Type)
     --code run to bake the cake of that type
     return "done"
end

Anything that follows the return is what is sent back. So in this case, “a” is equal to “done”

print(a)

Output:

“done”

2 Likes

Return also works for when you want a function to stop running even if there is code below.