示例工程 17-oop-patterns

17-oop-patterns/03-closure-object/main.lua

lua · 0.6 KB

-- @runtimes lua54 luajit
--- 演示:闭包对象,状态私有。
local M = {}
 
local function new_counter(start)
	local value = start
	return {
		inc = function()
			value = value + 1
			return value
		end,
		get = function()
			return value
		end,
	}
end
 
--- @return table { first = integer, second = integer, outside = nil }
function M.run(log)
	log = log or print
	local counter = new_counter(0)
	local first = counter.inc()
	local second = counter.get()
	log(("first=%d second=%d outside=%s"):format(first, second, tostring(counter.value)))
	return { first = first, second = second, outside = counter.value }
end
 
if not ... then
	M.run()
end
return M