gpt4 book ai didi

loops - Lua 尾调用 vs 循环

转载 作者:行者123 更新时间:2023-12-01 11:34:55 24 4
gpt4 key购买 nike

我正在用 Lua 编写一个小 CLI 模块以嵌入到 C 程序中。

我想知道处理提示的最佳方法是什么,在 之间进行选择尾随 循环 .

尾随 我会做这样的事情:

call = { help=function () print 'just ask politely' end }

function shell ()
io.write ('% ')
local cmd = io.read ()

if cmd ~= 'quit' then
call[cmd] () -- for simplicity assume call[cmd] is never nil
return shell ()
end
end

我会问以下问题:
  • 它是尾调用消除的正确使用/实现吗?是否 call[cmd] ()在堆栈中引入任何干扰,这样我就不会利用尾调用消除?
  • 使用 更好吗?循环 像下面这样?如果是,为什么?
    repeat
    io.write ('% ')
    local cmd = io.read()

    -- do stuff
    until cmd == 'quit'
  • 在 Lua 编程中说明

    A tail call is a goto dressed as a call.



    那么尾调用和循环之间有什么具体区别吗?

  • 谢谢你。

    最佳答案

    Is it a correct use/implementation of tail-call elimination?



    如果您询问是否调用 shell最后是根据 Lua 语法的正确尾调用, the answer is yes .

    Does call[cmd] () introduce any disturbance in the stack, so that I won't take advantage of the tail-call elimination?



    函数调用不会以您所想的方式修改堆栈。在 Lua 中,尾调用的唯一要求是格式为 return Function(params)。 ,没有不是函数返回值的额外返回值。

    一个适当的尾调用甚至不必调用它自己;它不需要是递归的。

    Is it better using a loop like the following? If yes, why?



    这是一个主观的观点。就个人而言,我会说循环对正在发生的事情更加清楚。

    但是,如果您想要一个客观的性能问题,请考虑这一点:尾调用永远不会比循环快。就性能而言,您将获得的绝对最佳值是相等的。

    而且很可能不会是这样。 Lua 尾调用“优化”仅仅意味着它重用了当前函数的堆栈条目。 Lua 仍然需要从全局表中获取函数。 Lua 仍然必须完成调用函数的所有开销;它只是不必分配更多的堆栈内存。

    这实际上是关于不溢出堆栈并且在不必要时不分配内存。

    is there any concrete difference between a tail call and a loop?



    往上看。

    关于loops - Lua 尾调用 vs 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11586250/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com