I've been learning to script, and I've gone over functions but I can't really get a good picture of what returning a function would really be used for.
I've also gone over numerous posts about returning and I still don't really get it. If someone can explain this thoroughly and easily, I'd love to have a simple answer and example to what returns are
Returning inside a function basically makes it stop and return a value that can be attributed to a variable
Lets say that I have this function:
function getRandomPlayer() local players = game.Players:GetPlayers() local selected = players[math.random(1, #players)] return selected end local plr = getRandomPlayer() print(plr.Name)
In that case, we are calling a function that use return
to "export" a variable from inside it.
Another way to use return is to stop a function from running:
local check = false function func() if not check then return -- stops the function if variable is false end print("Function running...") end func()
If this helps, please upvote and mark this answer as accepted
Returning is used to send informations back to where the function is called, here is an example:
local function sayHi() return "Hi!" end -- Print returned value of sayHi local returnedValue = sayHi() print(returnedValue)
Here is the expected output:
Hi!
You can also return using integers, as well as performing arithmetics.
local function multiply(x, y) return x*y end local returnedValue = multiply(5, 5) print(returnedValue)
25
Returning is very simple and easy to learn. Quick Recap: Returning is used to send informations to where the function is called, so whatever your returned value is, that value will get sent.
Returns are basically what you can get out of a function. Let's compare it to going to the store and paying for an item.
local function giveMoney(money) if money >= 10 then return "Some sweet shoes!" end end giveMoney(10)
In the function giveMoney
, it checks for the amount of money given. The example shows that you gave the function (or shopowner) 10 dollars. Since the shoes are 10 dollars, you are given some sweet shoes. Once that happens, you can show them off!
local function giveMoney(money) if money >= 10 then return "Some sweet shoes!" end end local shoes = giveMoney(10) print(shoes) -- Some sweet shoes!