So, I've seen return functions in some scripts. But I don't know what they do. I've seen videos of it, but I don't get them, so can someone explain return to me like I'm a toddler or something? I'll be grateful if you do!
Imagine a function as a machine, then imagine the return as what the machine gives back, or returns. For example:
local function foo() return 1 end print(foo())
What happens here is there's the machine is foo. We create the machine so now we can use it. The machine then gives back, or returns, the value of 1. So then we print to tell us what the value of foo is, printing 1.
However, we cannot try to get what the machine makes before even making the machine right? So this will not work:
print(foo()) local function foo() return 1 end
Now lets say this machine is given two slots, slot a
and slot b
. If we put something in these slots, the machine can use the values that we give it. These slots are called parameters, we can use them in a function as variables. The things we put in those slots are called arguments, for example:
local function foo(a, b) -- a and b are the two slots, or parameters return a + b end print(foo(1, 2)) -- 1 and 2 are the two arguments which we pass to foo
This outputs 3, because we put 1 and 2 in the a and b slots, then it returns a + b
, or 1 + 2
. You can also put other things in the slots too, for example you can put words in them, like this:
local function foo(a, b) return (a..b) end print(foo("Hello, ", "World!"))
This outputs Hello, World!
, in the two slots we give "Hello, "
and "World!"
, these are called strings, they're basically just strings of characters. Next they go on into the machine, "Hello, "
becomes a
and "World!"
becomes b
. Now you may be thinking, why is the machine using ..
instead of +
? This is just because in order to put two strings together you need to use ..
. A fancy phrase for this is called string concatenation. The return sends the value of the two strings concatenated back to print, which then prints it in the output.
Hopefully this helps!