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.
local function getTriangleArea(base, height) return (base * height)/2 end local area = getTriangleArea(7, 4)
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.
local dt, timeSinceProgramStarted = wait(3) print(dt, timeSinceProgramStarted) --> 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.
local pizzaPrice = 15 local function orderPizza(customer) if customer.Money.Value < pizzaPrice then return -- return out of the function if they do not have enough money end -- Function won't even reach here if the condition above was met. customer.Money.Value = customer.Money.Value - pizzaPrice -- give them their pizza end
Return is useful for many things. It can be used for not letting a player run through a script like this:
local canRun = false while true do if canRun ~= true then return end -- this would restart the script. 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:
local a, b = 1, 2 if a + b ~= 4 then return end --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:
function add(a, b) return a + b -- this would return the value of whatever a + b equates to end print(add(3, 4)) --the output would be 7
Hope this helped you out
giving or returinig gives back information when the function is called heres an example but this is useless
function add(num1,num2) return num1 + num2 end) print(add(1, 2))
this is giving back the answer it also stops the function if there was code after the return it wouldn't run