
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements