What exactly is returning and what is it generally used for?

Hi guys,
So this may be an unnecessary question to some of you,but I’ve had this problem for a long time now and I thought this would be the only way to solve it.
So,I’ve been watching lots of scripting tutorials for beginners and I’ve understood most of them,but there is this thing that may be simple to everyone but I don’t quite get and that is returning.
I just wanted to know what it is and in which cases do you use it because for all I know until now,you use it to add up two values.
If anyone would take their time to briefly explain it to me,I would really appreciate it since I can’t seem to understand it,even though I’ve tried my best.

2 Likes

You must understand functions first, assuming you do

function addNums(num1,num2)  -- creating a function to add two nums together


local addedNums = num1 + num2 -- creating a variable to add the two nums
return addedNums -- returning the VALUE of addedNums


end

print(addNums(2,2)) -- this will print 4 because the function is returning the value of 2 + 2
1 Like

Couldn’t you just print out num1 + num2 without using “return” though,that’s the part I find a bit vague.

Functions are generally for very complicated things. For example, say you have a placement system, and you need to use raycasting or something to check if you can place it. You can call the function, the function runs code to see if you can place it. If the function sees that you can place it, it will return true, if you cannot, it will return false.

You could, however, let us say you had a function that would give us a random brick color to assign a part

function RandomColor()
	
	
	
	local color1 = "Really red"
	local color2 = "Really blue"
	
	if math.random(1,2) == 2 then -- if a random number from 1 to 2 is equal to 2 then
		return color1 -- return "Really red" a BrickColor value
	else
		return color2 -- otherwise return "Really blue"
		
	end
	
	
end



game.Workspace.Part.BrickColor = BrickColor.new(RandomColor()) -- we call our RandomColor() function which will give us a color value to assign our part


end
1 Like