示例工程 07-functions-and-tail-calls

07-functions-and-tail-calls/05-function-value-table/main.lua

lua · 0.8 KB

-- @runtimes lua54 luajit
--- 演示:函数是一等值,可存入表并作为参数传递。
 
local M = {}
 
local function apply(fn, value)
	return fn(value)
end
 
local operations = {
	double = function(value)
		return value * 2
	end,
	negate = function(value)
		return -value
	end,
}
 
--- @return table { doubled = number, negated = number, composed = number }
function M.run(log)
	log = log or print
	local doubled = apply(operations.double, 4)
	local negated = apply(operations.negate, 4)
	local composed = apply(function(value)
		return operations.double(operations.negate(value))
	end, 3)
	log(("doubled=%d negated=%d composed=%d"):format(doubled, negated, composed))
	return { doubled = doubled, negated = negated, composed = composed }
end
 
if not ... then
	M.run()
end
 
return M