Hello, I have been watchin peasfactory, and I understand what he means when he explains returning. But, what is it useful for??
Heres his video about it------------
Return is a keyword, and what it does is either return a value from a function, prematurely end a function, or both.
1 | local function getTriangleArea(base, height) |
2 | return (base * height)/ 2 |
3 | end |
4 |
5 | local area = getTriangleArea( 7 , 4 ) |
The area
variable holds the "result" of the function. In this case the result is 14, because the function returns the area of a triangle. Not all functions have return values. Another example of a function that has a return value is wait
. Now this function has two return values; the delta time (time waited) and the time since the program started.
1 | local dt, timeSinceProgramStarted = wait( 3 ) |
2 |
3 | print (dt, timeSinceProgramStarted) |
4 | --> 3.00038384925, 3838.9 (just an example, you will get different numbers) |
You can prematurely end a function, if, for example, a condition is NOT met.
01 | local pizzaPrice = 15 |
02 |
03 | local function orderPizza(customer) |
04 | if customer.Money.Value < pizzaPrice then |
05 | return -- return out of the function if they do not have enough money |
06 | end |
07 |
08 | -- Function won't even reach here if the condition above was met. |
09 |
10 | customer.Money.Value = customer.Money.Value - pizzaPrice |
11 | -- give them their pizza |
12 | end |
Return is useful for many things. It can be used for not letting a player run through a script like this:
1 | local canRun = false |
2 |
3 | while true do |
4 | if canRun ~ = true then return end -- this would restart the script. |
5 | end |
EDIT: If you don't have a condition in which your script will run, calling return will stop the script forever. For example, this script would run halfway through, and then never run again:
1 | local a, b = 1 , 2 |
2 |
3 | if a + b ~ = 4 then return end |
4 |
5 | --random script (it doesn't matter whats down here because it won't run after the return |
return can also give us a value when used in a function, like this:
1 | function add(a, b) |
2 | return a + b -- this would return the value of whatever a + b equates to |
3 | end |
4 |
5 | print (add( 3 , 4 )) |
6 |
7 | --the output would be 7 |
Hope this helped you out
-Cmgtotalyawesome
giving or returinig gives back information when the function is called heres an example but this is useless
1 | function add(num 1 ,num 2 ) |
2 | return num 1 + num 2 |
3 | end ) |
4 | print (add( 1 , 2 )) |
3
this is giving back the answer it also stops the function if there was code after the return it wouldn't run