return is used in functions to, literally, return a value. Basically, you call the function, like normal, but return gives you something back. Because of this, the function actually becomes almost like a variable. Check it out:
function add(num1, num2)
return num1 + num2
end
local x = add(5, 2)
print(x)
See how we make x equal add(5, 2)? It's useful to note the distinction that we didn't make x equal the function itself -- we made x equal what the function returned after it ran.
return also stops everything -- loops, etc. Code after a return statement won't run.
We can return any type of value. In your case, we're returning another function. But it works the same as before -- the function is called, then it gives you something back. This 'something' just so happens to be another function.
The example I'm going to show is a situation where it's utterly pointless to return an extra function, but it should show how they work:
function makeFunc()
return function()
print("Hello, world!")
end
end
local x = makeFunc()
x()
This means that the following, although looking really weird, will be functional:
makeFunc()()
Comment with questions!
5 comments
It does exactly what it says, it returns a function! So you can call the letterIterator function and then call the function returned.
why do you need to return the function?
do you know what return means? It doesn't have to be function. It can be a variable.
but in this, does "return function()" create a new function or is it the letterIterator function?
a function is an object. it's returning an object. the object is a function. it's returning a function.