Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What does "return function()" do?

Asked by
CE13 0
8 years ago
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?

0
It does exactly what it says, it returns a function! So you can call the letterIterator function and then call the function returned. LetThereBeCode 360 — 8y
0
why do you need to return the function? CE13 0 — 8y
0
do you know what return means? It doesn't have to be function. It can be a variable. Vezious 310 — 8y
0
but in this, does "return function()" create a new function or is it the letterIterator function? CE13 0 — 8y
0
a function is an object. it's returning an object. the object is a function. it's returning a function. 1waffle1 2908 — 8y

1 answer

Log in to vote
3
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
8 years ago

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!

Ad

Answer this question