I always see return in scripts, and yes I know that they give a value to a function, but what can we use it for? Does anyone have a real-world example of what you can use it for? And can someone explain it to me better? Thanks!
When you use return, you're essentially storing a value to the function.
For example, typing
return 10
in a function sets the value of that function to 10, so that when you print the function you'll see the number 10 printed.
Take a look at this function.
1 | local function practiceFunction() |
2 | return 15 |
3 | end |
4 |
5 | print (practiceFunction()) |
We returned 15 to the function named practiceFunction, and then we printed practiceFunction, showing 15 in the output.
You can also return strings/text, boolean values like true and false, tables, and other data types.
Returns are useful is you want to get a value out of a function, but not use it right away.
1 | local function add(x,y) |
2 | print (x+y) |
3 | end |
4 |
5 | add( 5 , 7 ) |
Instead of printing 12 directly, we could store 12 into the function using return, letting us use 12 whenever we want to.
1 | local function add(x,y) |
2 | return (x+y) |
3 | end |
4 |
5 | --Many lines later...-- |
6 |
7 | print (add( 5 , 7 )) |
Returns are also used to escape a function if you don't add anything after it.
01 | local number = 6 |
02 |
03 | local function check() |
04 | if 5 +number = = 12 then |
05 | return |
06 | else |
07 | print ( "Change your number to 7" ) |
08 | end |
09 | end |
10 |
11 | check() |
If the variable number is 7 then it will return, exiting the function, not running the rest. However, if the variable number isn't 7 then it will print.
1 | function test(w) |
2 | return w |
3 | end |
4 |
5 | local func = test(workspace) |
6 |
7 |
8 | print (func) |
you can use it for returning values from a function
Heres an Example.
1 | function xD() |
2 | if workspace.FilteringEnabled = = true then |
3 | return |
4 | else |
5 | print ( 'WHY ISNT YOUR GAME FE!!??!!?!?!?' ) |
6 | end |
7 | end |
Return is pretty much an if else statement so,
1 | function test() -- your function you can name it anything |
2 | if part.Transparency = = 0 then -- just looking for a variable you can do any property |
3 | print ( "Transparency = 0" ) |
4 | return |
5 | else -- if thats not true it will output to this |
6 | print ( "Transparency test failed" ) |
7 | end |
8 | end |