function letterIterator(first, last) local index = first return function() if index <= last then index = index + 1 return string.char(index + 95) end end end
what does "return function()" do?
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) --> 7
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 is now the returned function x() --> Hello, world!
This means that the following, although looking really weird, will be functional:
makeFunc()()
Comment with questions!