Hello everyone, for a while now I’ve been stuck on trying to learn what return is and why is this useful or necessary to be in a script.
I tried reading about it in the Roblox documentations but still can’t understand.
Anyone can explain it to me? I wanna know what it does, why would I use it/why is it useful, where and when to use returning and if it’s even important for anything.
My TL;DR functions simplify code which is necessary in a script as it can get very complex. Return is good in functions to obtain the important information or result from the function.
local function CompareNumber(FirstNumber, SecondNumber)
if FirstNumber > SecondNumber then
return FirstNumber.." is greater then "..SecondNumber
elseif FirstNumber < SecondNumber then
return FirstNumber.." is less then "..SecondNumber
elseif FirstNumber == SecondNumber then
return FirstNumber.." is equal to"..SecondNumber
end
print(CompareNumber(1, 5)) --prints "1 is less then 5"
print(CompareNumber(42, 3)) --prints "42 is greater then 3"
print(CompareNumber(15, 15)) --prints "15 is equal to 15"
We are able to send data outside the function, with returning. We could make it into a Variable too like local ComparedValue = CompareNumber(15, 15) Which ComparedValue in this case would just be a string, “15 is equal to 15”, that we could use elsewhere then just printing (like putting it on a TextLabel etc.)
TL;DR:
In really simple words, return allows us to give data, to be used elsewhere, is how I think about returning.
Basically yes. Your function is getting all the children in the players service at the time the function is called, and not one player but it can be used…
local function test()
– blah blah
local player = game.Players:GetChildren()
return player
end
--Example of getting a random player from list:
local Players = test()
print(Players[math.random(1, #Players)].Name) --prints a random players name.
It’s also important to note that there can’t be any lines of code after a function returns once (besides ends and stuff. You can have if then statements and have more then one returns in a function though!)