What is the point of returning?

Recently, I have been learning how to script and I came across returning but I do not understand the point of it. Lets say you create a part in a function and you return it so that you can change its color to something else.

Well whats the point of that if you can just use the brackets/parenthesis at the end of the function to change its color instead?

If someone could explain this, it would be greatly appreciated.

You can read this

1 Like

The point of returning is to have access things that happen within the function. Lets say I have a function that creates a part like you said:

local function createPart(color)
    local part = instance.new("Part")
    part.Color = color
    part.Parent = workspace
end

createPart(Color3.new(1,0,0))

If you wanted to change the color you would have to do
workspace.Part.Color = Color3.new(0,1,0). Instead you could return the part and change the color.

local function createPart(color)
    local part = instance.new("Part")
    part.Color = color
    part.Parent = workspace

    return part -- return the variable "part"
end

local newPart = createPart(Color3.new(1,0,0))

we assign the variable “newPart” to the function because the function will return the part and the variable “newPart” is the part we just created. If we did the function again, it will just create another part, not change the color. I hoped this helped.

1 Like

It is a fundamental part of programming. It can stop lines earlier on a function. In other words, ceasing the scope entirely to later reference the value of it from a variable. e.g.

local a = function(x) 
    return x 

    print("this line is never printed")
end
local b = a(1)

print(a(20)) -- 20
print(b) -- 1

Also works as debounces, unlike break, which stops the scope of loops

1 Like

Functions are used to reuse part of code multiple times, without having to retype it every time you want it to execute. Returns are used to get values back from a function, mostly when you pass parameters into the function. You can then use those return values in different functions. For example:

function add(x,y)
     return x + y
end

function multiply(x,y)
     return x*y
end

local result = add(5,6)
print(multiply(result, 2))