Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Explain on how Return works and what it does?

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

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

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!

4 comments

1

Line 7 on your last script would error. Add a tostring()

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.

0

Okay.

0

Okay.

This discussion is preserved as it was. New answers, comments, and votes are closed.