Some time ago, when I was learning the Lua language, I read the Lua Chinese tutorial. When I read the closure section, I read it several times. The concept of closure is still very vague and I cannot clearly understand what it is going on.
I haven't been very busy with work recently, so I learned some knowledge about Lua by myself, but after only two hours of reading it, I encountered a problem - closure. Well, when I saw it, I thought it was related to close and the like. . . . (Forgive my ignorance)! But the more you look down, the more confused you become, so I read many things written by masters online to study and record them here so that I can’t see them in the future. . . . . Being despised
In lua, functions are also variables, which can be stored in tables, can be parameters of functions, or return values. In fact, a lua closure can be roughly understood as this. Closure (function name) {function abstraction, upvalue, env}, and function abstraction is the function body.
upvalue: is that an inline function can access all local variables that an outsourced function has created. These local variables are called external local variables or upvalue of the inline function. Upvalue actually refers to a variable rather than a value.
function newCounter() local i = 0 return function() i = i + 1 return i end end
In the above example i is an upvalue
Simply put, a closure is a function plus an upvalue that it can access correctly. upvalue is a local variable of an external function of a nested function. This function is generally defined inside another function; it can access member variables, parameters, and global functions defined in external functions. And this function can also return the function.
Tables and functions
one:
Lib = {} = function (x,y) retrun x+ y end = function(x)retrun x end;
two:
Lib = { foo = function (x,y) retrun x+ y end goo = function(x)retrun x end; }
three:
Lib = {} Lib = {} functio (x,y) retrun x+ y end function (x)retrun x end;
The above is the understanding of lua closures, tables and functions. Friends who need it can refer to it.