0

As per the guide(https://www.tutorialspoint.com/lua/lua_quick_guide.htm), which says that:

array = {"Lua", "Tutorial"}

function elementIterator (collection)

   local index = 0
   local count = #collection
    
   -- The closure function is returned
    
   return function ()
      index = index + 1
        
      if index <= count
      then
         -- return the current element of the iterator
         return collection[index]
      end
        
   end
    
end

for element in elementIterator(array)
do
   print(element)
end

What does closure function mean for Lua?

John
  • 2,963
  • 11
  • 33
  • Does this answer your question? [What is a 'Closure'?](https://stackoverflow.com/questions/36636/what-is-a-closure) – mkrieger1 Sep 23 '20 at 07:21
  • Closure is a function using local variables of its parent functions. For example, the function returned in your example depends on variables `index`, `count` and `collection`. – Egor Skriptunoff Sep 23 '20 at 07:23

1 Answers1

1

In Lua, any function is a closure. In a narrower sense, a closure is an anonymous function like the returned function in your example.

Closures are first-class: they can be assigned to variables, passed to functions and returned from them. They can be both keys and values in Lua tables.

Unlike PHP or C++, closures have access to all variables in local scope—upvalues (in your example, index and count, which keep the iterator state, and also collection) with no need to declare upvalues explicitly. Upvalues survive when code execution leaves the block where they were set.

You cannot write an iterator without a closure (or a subroutine). In your example (a simple iterator), elementIterator is a function that receives a table and returns another function, a closure. This returned closure is called again and again by the generic for instruction until it returns nil.

You may find this paper interesting: https://www.lua.org/doc/jucs17.pdf.

Alexander Mashin
  • 3,892
  • 1
  • 9
  • 15