Can someone explain to me how Return works in english because i don't get it. I understand it can return something into a variable but i just don't get the purpose.
Return can be used to return values, or to end a function prematurely, or both.
local function add(x, y) return x + y end print(add(7,6)) --13 local var = add(2,3) print(var) --5 local function searchTableForValue(tab, val) for i,v in pairs(tab) do if v == val then --ends the function and returns the index the value was found at return i end end return "Couldn't be found" --If the function ever gets to this return statement, it means it didn't find the value end
Returning is self-explanatory, but I'll attempt to go over it in-depth. It basically returns information and is usually used in functions, but it can be used in several other instances but that's more advanced.
For example, look at this example code:
function addNumbers(number1, number2) print(number1 + number2) end addNumbers(2, 5)
See, that will print out 7 because of the parameters we set which are 2 and 5.
However, what if you wanted to get that information and use it to change a text label? It's quite simple actually:
local text_label = script.Parent -- TextLabel location function addNumbers(number1, number2) return number1 + number2 end text_label.Text = addNumbers(2, 5)
See, you can actually use that data out of the function and it is very helpful, note that this isn't the only thing you can do with it. The options are endless!