lua-users home
lua-l archive

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


It was thus said that the Great bas @ lua-list once stated:
> > Consider my ctrace at
> > https://web.tecgraf.puc-rio.br/~lhf/ftp/lua/#ctrace
> 
> That’s a useful tool, which will aid my solution further; however I would
> like to do a similar thing with any and all Lua functions. i.e., I want to
> trace calls to `print` and the arguments+results of those calls, is there
> a way of using lua_Hook safely and having access to the arguments and
> results? Or is there a function in Lua I could “wrap” for this kind of
> tracing?

  Here's a proof-of-concept using the debug module from Lua:

	local function hook(what)
	  local info = debug.getinfo(2,'flnruS')
	  local f = info.name or string.format("%s:%d",info.source,info.currentline - 1)
	  print(what,f)
	  
	  if what == 'call' or what == 'tail call' then    
	    for i = info.ftransfer , info.ftransfer + info.ntransfer - 1 do
	      print("",debug.getlocal(2,i))
	    end
	    
	  elseif what == 'return' then    
	    for i = info.ftransfer , info.ftransfer + info.ntransfer - 1 do
	      print("",debug.getlocal(2,i))
	    end
	  end  
	end
	
	local function p(q,w,e)
	  print("","",q,w,e)
	  return true,false
	end
	
	local function a(x,y,z)
	  p(x,y,z)
	  return "foo",3
	end
	
	local function b(i,j,k)
	  -- return a(i,j,k) -- doesn't seem to display return data
	  local q,w = a(i,j,k)
	  return q
	end
	
	debug.sethook(hook,'cr')
	
	b("one","two","three")

  Tail calls seem to be a bit problematic, as the name isn't set properly,
and the return doesn't seem to be triggered properly, but aside from those,
this does what you asked for.

  -spc