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

Why does this code output this function? I thought functions only executes when told to?

Hello guys i am wonder why this code here prints "24" in the output I thought "numbers" was a variable and would only output if it was called this is really confusing as i am still starting out scripting. I dont understand how a variable can execute without being told to like print(numbers)

local function nas(x)
    print(x)
end

local numbers = nas(24) -- Outputs 24

I thought this would just make "x" = to 24 not execute the code without me calling the function like nas() why does this happen i dont get it, and when does it happen in code? thanks you

1 answer

✓ Accepted answer

How functions and variables work


The reason it prints 25 and numbers is nil, is due to the way variables and functions work.

local function nas(x)
	print(x)
end

local numbers = nas(24) 

The way functions in most languages work is by executing the code inside it with the arguments given until it hits the return function, which then returns whatever is after it and "terminates" the function\

In your case, you ran the function on line 5, then set variable numbers to what is returned by function nas, which is nothing, or nil.

For example:

local function foo (arg)
	print("Blah Blah Blah")
	return arg.." was supplied"
	-- print("ree") : won't run and will supply an error
end

local thing = foo("hi") -- Blah Blah Blah
print(thing) -- hi was supplied

This function print "Blah Blah Blah" when the function is called in line 7 and return arg.." was supplied" when given a string argument. Like shown with a print function in line 8

If I misunderstood your question, please leave a comment

Hopefully this helped! If it did, be sure to accept

1 comment

0

Thank you so much i understand now

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