跟踪Lua Sripts的执行

时间:2018-11-20 18:13:35

标签: debugging lua trace

我知道您可以使用lua的调试库来获取一些跟踪信息/调试信息。但是信息是零散的。所以我想知道是否有一种方法来跟踪Lua脚本的执行。逐步的过程。它是必需的,它将在每个执行步骤生成报告(例如以下内容)时自动进行;

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....

1 个答案:

答案 0 :(得分:2)

这是一些曾经在Lua tarball中分发的代码。从2005年开始,仍然可以正常使用。

-- 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