Simple Debugger

lua-users home
wiki


[!] VersionNotice: The below code pertains to an older Lua version, Lua 4. It does not run as is under Lua 5.

Lua provides tools for debugging, but they are not well advertised. You can use _ERRORMESSAGE to get a stack traceback and you can modify _ALERT to call debug so that you can examine global variables when an error occurs. With a little more code you can even dump out the local variables.[1]

This code[2] has a bug in it.

      1 require'simpledebugger.lua'
      2 
      3 function here( t, str, pat )
      4   assert( type(t,'table'), 'expecting a table' )
      5   assert( type(str,'string'), 'expecting a string' )
      6   pat = pat or '$(%b<>)'
      7   local f = function(w)
      8     local m = t[strsub(w,2,-2)] or w
      9     if type(m,'function') then m = m(t) end
     10     return tostring(m)
     11   end
     12   return( gsub( str, pat, f ) )
     13 end
     14 
     15 temp = [[ 
     16   this is a $<x> for $<y>
     17 ]]
     18 local tab = { x = 'test', y = 'fun' }
     19 write( here( tab, temp ) )
     20 write( here( temp, tab ) )
     21 print"game over"
If we run the code, we see that it dies due to a failed assertion.
$ lua -v testdebugger.lua 
Lua 4.1 (work4)  Copyright (C) 1994-2001 TeCGraf, PUC-Rio
 
  this is a test for fun
error: assertion failed!  expecting a table
stack traceback:
   1:  function `assert' [C]
   2:  function `here' at line 4 [file `testdebugger.lua']
   3:  main of file `testdebugger.lua' at line 20
lua_debug> 
We can dump out the locals at stack level 2 and we see that the function was called with the arguments switched.
lua_debug> locals(2)
t = " \
  this is a $<x> for $<y>\
"
str = { -- table: 0x80649b8
  y = "fun",
  x = "test"
}
pat = nil
lua_debug>
You can also dump out the locals further up the stack. Enter cont to quit out of debug.
lua_debug> locals(3)
tab = { -- table: 0x80649b8
  y = "fun",
  x = "test"
}
lua_debug> cont
If we add stop"it" just after line 8, we can inspect the variables in the function here.
$ lua -v testdebugger.lua 
Lua 4.1 (work4)  Copyright (C) 1994-2001 TeCGraf, PUC-Rio
error: it
stack traceback:
   1:  function <7:file `testdebugger.lua'> at line 9
   2:  function `gsub' [C]
   3:  function `here' at line 13 [file `testdebugger.lua']
   4:  main of file `testdebugger.lua' at line 20
lua_debug> locals()
w = "<x>"
m = "test"
lua_debug> cont
error: it
stack traceback:
   1:  function <7:file `testdebugger.lua'> at line 9
   2:  function `gsub' [C]
   3:  function `here' at line 13 [file `testdebugger.lua']
   4:  main of file `testdebugger.lua' at line 20
lua_debug> locals()
w = "<y>"
m = "fun"
lua_debug> cont
 
  this is a test for fun
game over


RecentChanges · preferences
edit · history
Last edited December 31, 2006 12:04 am GMT (diff)