New: Nitro Boost our Discord server and receive full donation perks here on the website! Join the Scripting Helpers Discord Server to learn more! You can also Support on Patreon as always.
Still have questions? Join our Discord server and get real time help.
1

What does 'return' do and how can I use it in my games?

I've been learning how to script this past week and I came across a lot of different terms but the one that confuses me the most is return. I've looked at multiple videos and websites to help me understand what returns are and what there used for but I'm still having trouble wrapping my head around it. If you can explain to me what returns are and how are they used in games I would really appreciate it.

0
Optikk 180
8 months ago

Functions aren't just reusable chunks of code. They can also "return" values. A (basic) example is this:

function addfive(n)
return n + 5
end

local ten = 10

print(ten, fifteen)


Returning is not limited to numbers. You can return anything. How about this function that finds a part which has the color "Really red"?

function findRedPart()
for _, v in pairs(workspace:GetChildren()) do
if v.BrickColor.Name == 'Really red' then
return v
end
end
end

local redPart = findRedPart()
redPart:Destroy() -- i hate red parts!


Or this function that returns a table of red parts???

function findRedParts()
local redParts = {}
for _, v in pairs(workspace:GetChildren()) do
if v.BrickColor.Name == 'Really red' then
table.insert(redParts, v)
end
end
return redParts
end

local redParts = findRedParts() -- now i can have all the red parts and destroy them all


The oppurtunities are limitless...

Though I'm sure someone else is gonna explain it better than me, that's the best I can do. I hope this helped a little.

0
Edited 8 months ago

The return keyword can do either 1 of 2 things or both things:

1. Ends the current thread function

2. Makes a function return a given value

If you give return nothing to return, it'll just end the function:

script.Parent.Touched:Connect(function(hit)
if game.Players:GetPlayerFromCharacter(hit.Parent) then
print(hit.Parent.Name)
else
return -- The function would end here
print("nothing found")
end
end)


If you give return a value, it'll make the function return that value AND it will still end the function:

function GetTouchingPlayer(hit)
if game.Players:GetPlayerFromCharacter(hit.Parent) then
return hit.Parent.Name
print("player found") -- This will not print because the previous line ends the function
end
end
script.Parent.Touched:Connect(function(hit)
local var = GetTouchingPlayer(hit)
print(var)
end)



return cannot be used to end statements.