Closure

The previous chapter introduced functions, and all functions in the Lua language are actually closures. This chapter introduces closures.

The so-called closure is the function prototype associated with some variables. In Lua, these associated variables are called Upvalue. If you understand closures in Rust, then according to "Rust Programming Language" it is "capturing environment" means the same thing as "associated variable". So Upvalue is fundamental to understanding and implementing closures.

The section 1 of this chapter introduces the most basic concept of Upvalue; the following sections 2 and 3 introduce the important feature of Upvalue, escape, which is what makes the closure really powerful; Section 4 introduces the Rust closure corresponding to the Rust function. The following sections 5 and 6 are the two application scenarios of closure and Upvalue respectively.