一天三盒半 发表于 2026-5-28 14:25:41

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实战用途:状态管理、限流、缓存、单次执行函数。


555666888 发表于 2026-5-28 16:07:31

收藏了,谢谢分享!
页: [1]
查看完整版本: Lua 进阶核心——闭包与 Upvalue