I dont understand if then return end

Hello, I am a scripter still learning and there is one thing I need help understanding

This thing I need help with is

if then return end

I’ve been looking on youtube and can’t find any thing related to it so please tell me what this does

Thank you!


Ah yes, the fabled return statement

Basically, this just cancels the entire function ahead of time before the lines ahead of it can run

Say I have this:

local Variable = 20

local function CheckVariable()
    if Variable == 20 then 
        print("This equals 20! CANCEL IT BEFORE THE FBI SPOTS IT")
    print("This variable is not equal to 20, you're safe!")


In our if statement check, if a certain conditional check is true, then we can return (Or end) our function early since it’s our Variable is equal to 20 & will print that FBI statement

If it isn’t however, we can assume that the variable is pretty much safe since our variable is equal to something else!


Oh wow thank you!
I will go test this in studio

This is probably the easiest way to understand how return works lol
And gotcha, lemme know what gets Outputted!

Also just when will we need this?

Well, it’s effectively the same in most cases as

if Variable ~= 20 then

but it only takes up a single line and doesn’t force you to indent your code. It’s good for a quick check at the top of a function to see if data is missing or some condition that would cause the function to error. It’s cleaner to abort rather than indent everything and match up another end.

Oh so if then return end is like breaking the function?
I actully am curious and see if you there can be anything printed after the function has been called

If you just wanna stop a certain function from preventing its other lines of code from running inside the function, you can just cancel the function early by using return

(Or what Jarod stated earlier)

Wow thats great because you can only break loops using break

1 Like

A long time ago, I also didn’t understand when it was needed and it took a month to finally learn why I needed it.

This is when you need it.

local function AddNumbers(firstNumber,secondNumber)
	return firstNumber + secondNumber

local onePlusThree = AddNumbers(1,3)

--return returns something to the item that calls it

local function countTable(tbl)
	return #tbl

allowed = false
if not allowed then
	print("access granted")
--it can also end something

I knew what returning was in general but thanks for the 2nd example!