示例工程 07-functions-and-tail-calls
07-functions-and-tail-calls/03-tail-call-stack/main.lua
-- @runtimes lua54 luajit
--- 演示:尾调用不增长栈,非尾调用增长。
local M = {}
local function tail(n, acc)
if n == 0 then
return acc
end
return tail(n - 1, acc + 1)
end
local function non_tail(n)
if n == 0 then
return 0
end
return 1 + non_tail(n - 1)
end
--- @return table { tail_depth = integer, non_tail_value = integer }
function M.run(log)
log = log or print
local depth = 5000
local tail_value = tail(depth, 0)
local non_tail_value = non_tail(100)
log(("tail_value=%d"):format(tail_value))
log(("non_tail_value=%d"):format(non_tail_value))
return { tail_depth = depth, non_tail_value = non_tail_value }
end
if not ... then
M.run()
end
return M