Lua 进阶核心——闭包与 Upvalue
闭包 = 函数 + 它捕获的外部局部变量(Upvalue)特点:变量持久化、私有化、工厂函数。
示例:独立计数器
function makeCounter()
local count = 0-- 私有变量
return function()
count = count + 1
return count
end
end
local c1 = makeCounter()
local c2 = makeCounter()
print(c1(), c1(), c2())--> 1 2 1实战用途:状态管理、限流、缓存、单次执行函数。
收藏了,谢谢分享!
页:
[1]