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.
local function practiceFunction() return 15 end 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.
local function add(x,y) print(x+y) end 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.
local function add(x,y) return(x+y) end --Many lines later...-- print(add(5,7))
Returns are also used to escape a function if you don't add anything after it.
local number = 6 local function check() if 5+number == 12 then return else print("Change your number to 7") end end 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.
function test(w) return w end local func = test(workspace) print(func)
you can use it for returning values from a function
Heres an Example.
function xD() if workspace.FilteringEnabled == true then return else print('WHY ISNT YOUR GAME FE!!??!!?!?!?') end end
Return is pretty much an if else statement so,
function test() -- your function you can name it anything if part.Transparency == 0 then -- just looking for a variable you can do any property print("Transparency = 0") return else -- if thats not true it will output to this print("Transparency test failed") end end