示例工程 13-closures-and-upvalues

13-closures-and-upvalues/01-shared-upvalue/main.lua

lua · 0.5 KB

-- @runtimes lua54 luajit
--- 演示:多个闭包共享同一个 upvalue。
local M = {}
 
--- @return table { first = integer, second = integer, third = integer }
function M.run(log)
	log = log or print
	local count = 0
	local function inc()
		count = count + 1
		return count
	end
	local function get()
		return count
	end
	local first = inc()
	local second = inc()
	local third = get()
	log(("first=%d second=%d third=%d"):format(first, second, third))
	return { first = first, second = second, third = third }
end
 
if not ... then
	M.run()
end
return M