Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can someone explain me how the function "return" works?

Asked by 6 years ago

I've seen script use the term "return" before, but I don't get it even after looking in the official lua page. Can you please explain me how it works, exactly?

P.S If return isn't a function just ignore it, I need it to post this xd

0
Return could be used for this for example: return end, return false and true <--- i think return end is working tho. DevelopingUnlimited -6 — 6y

2 answers

Log in to vote
0
Answered by 6 years ago

So yeah. I had a lot of trouble figuring out what return does. So I hope I can help you out with this explanation: First of all return allows you to use a function like a variable here is an example:

function randomNumber()
    return math.random(1, 10)
end
local number = randomNumber()
print(number)
-- would output a random number between 1 and 10
-- you could also do this:
print(randomNumber())
-- would output a random number between 1 and 10

another benefit of return is it ends the function when it is called. Like in this example admin script:

local adminList = {"Plieax", "Bob", "Joe"} -- names are examples

    function checkIfPlayerIsAdmin(player) -- will equal false if the player is not an admin like a variable as I said above
    for i,v in pairs(adminList) do
        if v == player.Name then
            return true -- will end the loop right away and the function will be a variable which = true
        end
    end
    return false -- if the function is not ended by the return true above in the for loop then the function will be a variable that = false
end
game.Players.PlayerAdded:connect(function(player)
    if checkIfPlayerIsAdmin(player) then
        print("PlayerIsAdmin")
    end
end)

You can return any type of value a number, boolvalue, string, table, function, variable and so on. If you have anymore questions just comment below. I hope this helped. Have a great day scripting!

0
Oh I see, thanks for helping :D SirDerpyHerp 262 — 6y
0
No problem! User#21908 42 — 6y
Ad
Log in to vote
2
Answered by 6 years ago
Edited 6 years ago

Not sure what you mean with 'P.S If return isn't a function just ignore it, I need it to post this xd" . Return are used for a few things, you probably most of the time see it inside functions

A quick example

function MultiplyBy2(Val)
    if Val then
        return Val * 2
    end
end

local Val = MultiplyBy2(2)
print(Val) --> 4

It basicly creates a return value, you can have multiple return values too, or you can return a table

Also, modules can have return values too, that's the reason you should use modules. You can return a value the same way as the function above

0
I always use it in an "if" statement GamingZacharyC 152 — 6y

Answer this question