- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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.
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
1 2 1 3 2
- What does # mean in Lua programming?
- Comments in Lua Programming
- What are some of the important Scientific Libraries used in Lua programming?
- table.pack() function in Lua programming
- table.unpack() function in Lua programming
- Lexical Conventions in Lua Programming
- math.ceil() function in Lua programming
- math.floor() function in Lua programming
- math.max() function in Lua programming
- math.modf() function in Lua programming
- select() function in Lua programming
- Semicolon Conventions in Lua Programming
- Sort function in Lua programming