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

I dont understand how return is different from just using things?

for example return print('Noob')

we can write less things if we just print('Noob') its still going to do the same thing and function well

I don't see the use of return can anyone tell me what return is used for? or what its useful for?

1 answer

The return keyword

The keyword return has two main purposes:

  • Stop a function or if statement.
  • Return the results of the function that ran.

You don't need to use return if the function ends naturally (ending via its end keyword). If the function does not end naturally (for example, if a loop is inside of the function) then you would use return.

return is similar to break in the way that it stops something. While break stops the current thread loop, return stops the current thread function. Here's what I mean:

game.Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
	    return -- This return stops the CharacterAdded function, but not the PlayerAdded function
    end)
	return -- This return stops the PlayerAdded function
end)

As compared to how break works:

while true do
    wait()
	for i = 1, 10 do
		wait()
		print(i)
		if i == 5 then break -- This break stops the for loop but it does not stop the while loop
	end
	break -- This break stops the while loop
end

If a function doesn't return anything but you want it to return something, that's also when you use the return keyword:

local function FindRadiusOfCylinder(cylinder)
	return (cylinder.Size.Z / 2)  -- Returns the radius to the part of the code that calls the function
end
FindRadiusOfCylinder(workspace.Tube)    

That's what you need to know about return.

To get the returned value:

You can print it:

local radius = FindRadiusOfCylinder(workspace.Tube)
print(radius)

This should print the radius of the cylinder.

2 comments

0

You should also add how to receive the returned value other than that nice

0

Good point, let me do that.

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