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

What is returning useful for?

Asked by 9 years ago

People always tell me you need to learn returning but IDK what for...

2 answers

Log in to vote
1
Answered by 9 years ago

Basically the return command will take you out of the function immediately.

function eatCheese()
    if 2+2=4 then
        print("woohoo")
    else
        print("I hate life")
        return --ends the function
    end
print("function is also done") -- could also end here if 2+2=4 is true
end

If you specify an object, such as a boolean with return, it will return that boolean. So basically, it will also set the function equal to what you returned.

function eatPizza()
    return true  --returns the value true
end

if eatPizza() == true then --eatPizza() returns true, so it would work here
    --content
end
0
Also, you can't have another function right after a return, it won't execute. Laserpenguin12 85 — 9y
0
It would be cool if it could though. I believe line two of your first script should be 2+2 == 4 as it would then be "is equal" to 4 (not on computer, can not check). Also the first script is missing a end and it would not be ran as it is never called. Line 5 of your second script, function is used to define a new function, so just remove it or else the script will through a error eatPizza() I woul M39a9am3R 3210 — 9y
0
...would recommend to be in that if then statement. M39a9am3R 3210 — 9y
0
Also, Returns are useful for Generic for loops. Laserpenguin12 85 — 9y
0
Thanks M39, I didn't notice I declared the function again and forgot to end the first one >.< randomsmileyface 375 — 9y
Ad
Log in to vote
1
Answered by
funyun 958 Moderation Voter
9 years ago

returning in a function allows you to use the function like a value. Examples:

function mathstuff(x)
    return 2*x + 5
end

print(mathstuff(3)) --Using the function as a value.
function equal(a, b)
    return a == b
end

if equal(4, 2 + 2) then
    print("2 + 2 = 4")
end
function a(text) --Declare a
    return "MWA"..text --Add "MWA" to the beginning of "HAHAHA".
end

function b(text) --Declare b
    return a(text:rep(3)) --Repeat "HA" 3 times (or twice, technically) and send to a
end

function c(text) --Declare c
    return b(text:upper()) --Make "ha" uppercase, send it to b
end

print(c("ha")) --Call c, "text" in c is "ha"
--Returning nil, or just returning with nothing there,
--basically means you're cancelling out of the function.
--This lets us continue on in the script without errors.

function square(argument)
    if type(argument) ~= "number" then
        return --Return nothing, so we don't continue in the function.
    else
        return argument^2
    end
end

print(square("hi")) --You can't square "hi".
print(square(5)) --You can square 5 though!

Answer this question