Hey. I learned returning when I was a starter, and it's all fine. But lately I feel I do not know the meaning of returning and what it does so well. I use it rarely, and I use a lot of functions in my scripts. I feel maybe I got the wrong knowledge from a wrong website, or whatever. Can someone tell me what they are used for and give me an example? Thanks.
The return
keyword prepares the function to give back a result. In most cases, with no procedures that provide a finished result, these functions just become what’s known as a void
method.
Let’s take a look at a few examples of where we would apply return in daily code:
01 | --// Mathematics |
02 | local function multiplyNumber(number, multiple) |
03 | return number*multiple |
04 | end |
05 |
06 | local fiveTimesFour = multiplyNumber( 5 , 4 ) |
07 | print (fiveTimesFour) --// 20 |
08 |
09 | --// Boolean condition |
10 | local function booleanCondition(Expression) |
11 | if (Expression) then |
12 | return true |
13 | end |
14 | return false |
15 | end |
16 |
17 | if (booleanCondition(workspace.Part:IsA( "Part" )) then |
18 | print ( "Is a Part!" ) |
19 | end |
return
will stop the function immediately, anything within the scope below will not run.
here you can understand with my script:
1 | function rturn() |
2 | print ( "hi" ) |
3 | return 1 |
4 | end |
5 |
6 | game.Workspace.scarp.Transparency = rturn() |
When returned is active, it stops the function like a break in loops, return turns the function into a variable, return gave the function variable 1 to its value, therefore we change the transparency of Scrappy The Part. You can store the function in a variable like
1 | Rat = rturn() |
2 | game.Workspace.scarp.Transparency = Rat |
Return is a good way to get data from a function. You won't need it too often, but every once in a while is a good thing. For example:
01 | function returnHumanoid(part) |
02 | local humanoid = part.Parent:FindFirstChild( "Humanoid" ) |
03 |
04 | if humanoid then |
05 | return true |
06 | else |
07 | return false |
08 | end |
09 | end |
10 |
11 | local isHumanoid = returnHumanoid(randomPart) |
return is a thing which returns values such like this:
1 | local function plus(A,B) |
2 | return A*B |
3 | end |
4 |
5 | local number = plus( 1 , 1 ) |
6 |
7 | print (number) |
8 |
9 | --> the thing got printed is 2 |