Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

does return do anything besides print and break? [closed]

Asked by
MEWTLC 0
4 years ago
Edited 4 years ago

if so, what does it do?

1
Also, I'd advise you to do some more research! JesseSong 3916 — 4y
0
bomblitz06 and Benbebop gave good answers on this. Returns are also imperative for module scripts. SteelMettle1 394 — 4y

Locked by JesseSong

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

3 answers

Log in to vote
3
Answered by
Benbebop 1049 Moderation Voter
4 years ago
Edited by JesseSong 4 years ago

Neither

A common misconception is that return is for breaking loops, this is not the case. If your goal is to break a loop use break as that is its intended function.

It should be noted return technically can be used to break a code block, though it still should not be used in that situation as end already serves that exact purpose.

Return is instead used in functions, to take information from a function and allow it to be used wherever the function was called originally.

Return ends the function, causing the script to go back to where the function was called originally. This allows a returned value of one function to be used inside a second function.

Ex.

1function divide(num1, num2)
2    local result = num1 / num2
3    return result
4end
5 
6print(divide(1, 2))

When this code is run, it will print 0.5

Credits:

  • Benbebop (the whole thing)
  • JesseSong (correcting some minor errors)
Ad
Log in to vote
2
Answered by 4 years ago
Edited 4 years ago

Return basically turns the function call into the returned object It's hard to explain, so here are some examples

01local function returnHelloWorld()
02    return "Hello World!"
03end
04 
05local var = returnHelloWorld()
06 
07print(var) -- The function returned "Hello World!" to the variable var, so this should output var, which is Hello World!
08 
09-- --
10 
11local function addTwoNumbers(number1, number2)
12    local added = number1 + number2
13    return added
14end
15 
16print(addTwoNumbers(5, 10)) -- The function returned the variable added, and the variable added is number1 + number2. from the function call, number1 is 5 and number2 is 10, so this should output 5 + 10, which is 15
Log in to vote
1
Answered by 4 years ago

Please provide explanation with your answers. Simply posting code does not spread knowledge of integral scripting processes which helps people understand the logic and reasoning behind your answer.

Return is very useful when calling functions, you can pass information back to the area which called it from so you can do

01Local function thing()
02    Local result = ---some code
03    Return result
04End
05 
06If thing() then
07--do something if result is true
08Else
09--do something else
10End

I'm on mobile so I can't explain too well atm, read more here