lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]





On Tue, Aug 5, 2014 at 11:25 AM, Coda Highland <chighland@gmail.com> wrote:
On Tue, Aug 5, 2014 at 9:19 AM, Sean Conner <sean@conman.org> wrote:
> It was thus said that the Great Roberto Ierusalimschy once stated:
>> >   I don't know.  This
>> >
>> >     x = 5
>> >     function F(...)
>> >       return F(x,...)
>> >     end
>> >
>> >     print(F())
>> >
>> > is taking an awful long time to fail.
>
>   By "long time to fail" I mean "it's stuck in an infinite loop."
>
>> I believe this is O(n^2), as each new call copies all accumulated
>> arguments. Change your function to this and you will see the
>> slowdown:
>>
>> local x = 0
>> function F(...)
>>   x = x + 1
>>   print(x)
>>   return F(x,...)
>> end
>>
>> print(F())
>
>   I did that, and it's currently stuck (20 minutes) in an infinite loop.
>
>   -spc (Tail calls for the win!)

It shouldn't be infinite. When the function call accumulates enough
parameters to overflow the stack, it should fail.

/s/ Adam


```
local x = 0
local function F(...)
    x = x + 1
    if select("#", ...) > 10 then
        error("look at my stack trace and see if it has tail calls in it")
    end
    return F(x,...)
end

F()
--[[
lua.exe: myfile.lua:5: look at my stack trace and see if it has tail calls in it
stack traceback:
[C]: in function 'error'
C:\trms\packages\mediacircus\testing\presentation_state.lua:5: in function <C:\trms\packages\mediacircus\testing\presentation_state.lua:2>
(...tail calls...)
C:\trms\packages\mediacircus\testing\presentation_state.lua:10: in main chunk
[C]: in ?
--]]
```

-Andrew