Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

1 comment

0

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

2 answers

✓ Accepted answer

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!

2 comments

0

Oh I see, thanks for helping :D

0

No problem!

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

1 comment

0

I always use it in an "if" statement

This discussion is preserved as it was. New answers, comments, and votes are closed.