What are Closures in Lua Programming?


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 C++ or PHP, closures in Lua have access to all variables in local scope— upvalues with no need to declare upvalues explicitly. Upvalues survive when code execution leaves the block where they were set.

Now that we know what a closure is and why it is useful, let’s take an example and see how it works.

Example

Consider the example shown below −

 Live Demo

function simpleCounter()
   local i = 0
   return function () -- anonymous function
      i = i + 1
         return i
      end
   end
c1 = simpleCounter()
   print(c1()) --> 1
   print(c1()) --> 2
c2 = simpleCounter()
   print(c2()) --> 1
   print(c1()) --> 3
   print(c2()) --> 2

Output

1
2
1
3
2

Updated on: 19-Jul-2021

739 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements