Closure的“非局部变量”
function newCounter()
local i = 0
	return function()
		i = i+1
		return i
	end
end

c = newCounter()
print(c()) --1
print(c()) --2
c2 = newCounter()
print(c2()) --1
print(c()) --3
print(c2()) --2


在newCounter中返回了一个闭合函数,使用到了一个newCounter的局部变量i,但是返回的闭合函数使用的i是保留存在的

调用新的newCounter会产生一个新的i,值是独立的,看上面代码的输出。


首页 我的博客
粤ICP备17103704号