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
3 years ago
Edited 3 years ago

if so, what does it do?

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

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
3 years ago
Edited by JesseSong 3 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.

function divide(num1, num2)
    local result = num1 / num2
    return result
end

print(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 3 years ago
Edited 3 years ago

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

local function returnHelloWorld()
    return "Hello World!"
end

local var = returnHelloWorld()

print(var) -- The function returned "Hello World!" to the variable var, so this should output var, which is Hello World!

-- --

local function addTwoNumbers(number1, number2)
    local added = number1 + number2
    return added
end

print(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 3 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

Local function thing()
    Local result = ---some code 
    Return result
End

If thing() then
--do something if result is true
Else
--do something else
End

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