How does returning functions work?

hi im somewhat new to coding/scripting and im having trouble understanding it despite watching yt vids and reading the wiki,can anyone explain it to me a bit? thx

2 Likes

What do you mean by “returning” a function? Are you talking about the return used in functions, or are you talking about return ExampleFunction()?

Return statements allow your function to take inputs and then return an output. Think of having a function that adds two numbers. You want that sum of those two number to be sent back so you can use it in your script. Or you can use it on it’s own as a way to escape a function early, I will show both examples below.

local function addNumbers(number1,number2)
   return number1 + number2
end

print(addNumbers(1,3)) --This prints 4
local function isThisNumberFive(number)
   if number ~= 5 then
      return
   else
      print("The number is 5!")
   end
   print("End function")
end

isThisNumberFive(1) --Prints nothing
isThisNumberFive(5) --Prints both print statements
6 Likes

the return that is used in functions

1 Like
local function getEquippedPet()
   local EquippedPet = blablahblah
--code
   return EquippedPet
end
local CurrentEquippedPet = getEquippedPet()
if CurrentEquippedPet  then
--code
end

Here you go.

I had this exact same problem when I was learning how to script, seems like no matter where I went, I just could not find the answer.

Short Answer:

Returns are used to “return” a value to the place the function was called

Long Answer

One of the ways I use this alot is to speed up making certain parts. For example


function MakeInstance(Type, Parent)

local ins = Instance.new(Type, parent)
return ins

end

local Part = MakeInstance(Part, workspace)

In this, the MakeInstance function will make the part I clarify in the parameters then send it back to where the function was called.

Did you do a search before posting this? :confused:

2 Likes

so its for returning a variable/result and be able to use it again in the script? getting it a bit better but not quite yet

It is basically setting a value to a function.

local function myFunction(int)
return int
end

print(myFunction("hello"))

Expected output:
hello

Exactly, lets try one more example…


function Add(x,y)

return x+y

end

local Sum = Add(4,5)

So this will take those 2 numbers you send, add them together, and then return them as the added value.

3 Likes

thx man this helped alot , ill try coding something simple see if I understood properly

1 Like

I got the result I wanted, Thx!

1 Like