Search code examples
debuggingluatrace

Tracing execution of Lua Sripts


I know you can use the debug library of lua to get some tracing info/debugging. But the information is in pieces. So I am wondering if there is a way to trace the execution of a Lua script. A step by step process. it would be required and it will automatically go thru at every execution step To produce a report such as the following;

Called: function xyz  from : Table abc
It has n parameters
Param 1: apples
Param 2: oranges
.
.

It has m returns
return 1: red
return 2: yellow
.
.

Called: function xyz2  from : Table abc2
It has n parameters
Param 1: pears
Param 2: bananas
.
.
It has m reruns
return 1: heavy
return 2: light
.
.

and so on....

Solution

  • Here is some code that used to be distributed in the Lua tarball. It's from 2005 and still works fine.

    -- trace calls
    -- example: lua -ltrace-calls bisect.lua
    
    local level=0
    
    local function hook(event)
     local t=debug.getinfo(3)
     io.write(level," >>> ",string.rep(" ",level))
     if t~=nil and t.currentline>=0 then io.write(t.short_src,":",t.currentline," ") end
     t=debug.getinfo(2)
     if event=="call" then
      level=level+1
     else
      level=level-1 if level<0 then level=0 end
     end
     if t.what=="main" then
      if event=="call" then
       io.write("begin ",t.short_src)
      else
       io.write("end ",t.short_src)
      end
     elseif t.what=="Lua" then
      io.write(event," ",t.name or "(Lua)"," <",t.linedefined,":",t.short_src,">")
     else
     io.write(event," ",t.name or "(C)"," [",t.what,"] ")
     end
     io.write("\n")
    end
    
    debug.sethook(hook,"cr")
    level=0