Mircode
Mircode

Reputation: 746

lua debug hook causing race condition?

I wanted to report some debug information for a parser I am writing in lua. I am using the debug hook facility for tracking but it seems like there is some form of race condition happening.

Here is my test code:

enters = 0
enters2 = 0
calls = 0
tailcalls = 0
returns = 0
lines = 0
other = 0
exits = 0

local function analyze(arg)
    enters = enters + 1
    enters2 = enters2 + 1

    if arg == "call" then
        calls = calls + 1
    elseif arg == "tail call" then
        tailcalls = tailcalls + 1
    elseif arg == "return" then
        returns = returns + 1
    elseif arg == "line" then
        lines = lines + 1
    else
        other = other + 1
    end

    exits = exits + 1
end

debug.sethook(analyze, "crl")

-- main code

print("enters = ", enters)
print("enters2 = ", enters2)
print("calls = ", calls)
print("tailcalls = ", tailcalls)
print("returns = ", returns)
print("lines = ", lines)
print("other = ", other)
print("exits = ", exits)

print("sum = ", calls + tailcalls + returns + lines + other)

and here is the result:

enters =        429988
enters2 =       429991
calls =         97433
tailcalls =     7199
returns =       97436
lines =         227931
other =         0
exits =         430009
sum =   430012

Why does none of this add up? I am running lua 5.4.2 on Ubuntu 20.04, no custom c libraries, no further messing with the debug library.

Upvotes: 1

Views: 143

Answers (1)

Mircode
Mircode

Reputation: 746

I found the problem...

The calls to the print function when printing the result also trigger the hook, which only affects the results that have not been printed yet.

Upvotes: 3

Related Questions