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

Explain on how Return works and what it does?

Asked by 6 years ago

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.

2 answers

Log in to vote
3
Answered by
theCJarmy7 1293 Moderation Voter
6 years ago
Edited 6 years ago

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
Ad
Log in to vote
3
Answered by 6 years ago

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!

1
Line 7 on your last script would error. Add a tostring() User#19524 175 — 6y
0
Actually, I was gonna add tostring() but I thought he would get confused, but I tested it in studio beforehand and it worked just fine. YabaDabaD0O 505 — 6y
0
Okay. User#19524 175 — 6y
0
Okay. User#19524 175 — 6y

Answer this question