https://blog.csdn.net/sbddbfm/article/details/94424695 参考文章
闭包:有一个函数和该函数会访问到的非局部变量(且不是全局变量)(或者upvalue)组成的。
就是说这个函数取变量取不到的时候就会向从他上级函数里找,找到后哪怕上级函数没有再执行了,但是这个变量还存在。
闭包是运行的时候形成的,运行的时候upvalue会单独开辟一块内存来存放
local baseFunc = {}
baseFunc.create = function (n)
local i = 0
return function ( )
n=n+1
print(n)
i = i+1;
print("i=",i)
end
end
local f1 = baseFunc.create(100)
f1()
f1()
local f2 = baseFunc.create(200)
f2()
f2()
local i = 1
repeat
name, val = debug.getupvalue(f1, i) --获取upvalue的值
if name then
print ("index", i, name, "=", val)
if(name == "n") then
debug.setupvalue(f1,2,10) --修改upvalue的值
end
i = i + 1
end -- if
until not name
f1()
image.png
网友评论