lua-users home
lua-l archive

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


On 6 June 2016 at 02:40, Nagaev Boris <bnagaev@gmail.com> wrote:
> On Sun, Jun 5, 2016 at 4:11 PM, Daurnimator <quae@daurnimator.com> wrote:
>> In Lua 5.1.5 I get:
>> return
>> call
>> call
>> return
>> tail return
>> return
>>
>> In Lua 5.3.2 I get:
>> return
>> call
>> tail call
>> return
>> return
>>
>> The first `return` in both outputs is debug.sethook itself returning,
>> the final `return` in both outputs is the test itself finishing. These
>> can be ignored for the sake of your example.
>>
>> In 5.1 if you count +1 for each "call", and -1 for each "return" or
>> "tail return" it is balanced:
>> 0
>> call --> 1
>> call --> 2
>> return --> 1
>> tail return --> 0
>>
>
> Hello,
>
> I increased depth of tail calls:
>
> local function identity(n, result)
>     result = result or 0
>     if n == 0 then
>         return result
>     else
>         return identity(n - 1, result + 1)
>     end
> end
> debug.sethook(print, "cr")
> print(identity(1000))
>
> Results:
>
> $ lua5.1 identity.lua > /log
> $ grep -c -w call log
> 1003
> $ grep -c -w return log
> 1006
>
> $ lua5.2 identity.lua > /log
> $ grep -c -w call log
> 1003
> $ grep -c -w return log
> 6
>
> $ lua5.3 identity.lua > /log
> $ grep -c -w call log
> 1003
> $ grep -c -w return log
> 6
>
> $ luajit identity.lua > /log
> $ grep -c -w call log
> 1002
> $ grep -c -w return log
> 2
>
> Only Lua 5.1 produces balanced results.

In 5.2+ (as my paste showed with 5.3) the new event "tail call" event
is introduced.
It counts counts a call and a return in one.
Your 'grep' is counting it as it contains "call".

> By the way, how it gets this
> information for tail calls without using additional stack space? Does
> it store only an integer (depth)?

Yes.