Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

What does "return function()" do?

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?

5 comments

0

It does exactly what it says, it returns a function! So you can call the letterIterator function and then call the function returned.

0

why do you need to return the function?

0

do you know what return means? It doesn't have to be function. It can be a variable.

0

but in this, does "return function()" create a new function or is it the letterIterator function?

0

a function is an object. it's returning an object. the object is a function. it's returning a function.

1 answer

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!

This discussion is preserved as it was. New answers, comments, and votes are closed.