I've tried watching a couple of videos on it, but they don't explain it very well. Can someone give me a bit more detail of how it works other than what the scripting glossary says?
Return
is a keyword that is used to send information back to the line that called a function. For example, the following would call the A function and will print the number, while the B function will not result in anything being printed and may error.
function A() num = math.random(1,10) return num end function B() num = math.random(1,10) end print(A()) -- will print what is after "return" on line 2, in this case it is num, a random number from 1-10 print(B()) -- will not print anything as the number is not being sent back to the function call
Return
can be used in many ways, a very common way is with ModuleScripts. When a LocalScript or a Server Script use Require
to get a module from a ModuleScript, the ModuleScript will return the information from the module so that the other scripts can use it.
You can think of return as asking somebody for information, that person telling you some information after you ask, and then you listening to what they tell you.
Return
was one of the oddest things for me to learn because nowhere it was really explained well and I didn't really learn it up until about a year ago when I took a class on C++ in which syntax similar to Return was explained in detail. If you need more help understanding it, I would gladly help you understand better.
Functions are a really awesome feature of programming languages brought in from mathematics.
Functions take in values and put out values.
An example is square root -- you put in 25 and get out 5. In Lua, that function is math.sqrt
. Using it looks like this:
local five = math.sqrt( 25 )
Another example of a function would be something that doubles a number. You put in x
and get out x * 2
. How would we write that function in Lua?
function double(x) -- `x` is the thing coming in return x * 2 -- `return` marks the thing going out end local six = double(3)
We declare that a block of code is a function using the function
keyword. The next word is the name of the function, followed by all the parameters -- the values coming in.
Next comes the code for the function. The value after the keyword return
is the value going out of the function.