簡易除錯器

lua-users home
wiki


[!] VersionNotice:下列程式碼是專屬於舊版的 Lua 版本,Lua 4。它無法在 Lua 5 中執行。

Lua 提供了除錯工具,但它們並未廣為宣傳。你可以使用 _ERRORMESSAGE 來取得堆疊追蹤,並修改 _ALERT 以呼叫 dubug,這樣你就可以在發生錯誤時檢查全域變數。透過再增加一些程式碼,你甚至可以傾印出局部變數。 [1]

此程式碼 [2] 有個錯誤。

      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"
如果我們執行程式碼,我們會看到它因為錯誤的斷言而發生錯誤。
$ 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> 
我們可以在堆疊層級 2 中傾印出局部變數,我們會看到該函數是以交換的參數呼叫的。
lua_debug> locals(2)
t = " \
  this is a $<x> for $<y>\
"
str = { -- table: 0x80649b8
  y = "fun",
  x = "test"
}
pat = nil
lua_debug>
你也可以向上傾印堆疊中更上層的局部變數。輸入 cont 以退出 dubug
lua_debug> locals(3)
tab = { -- table: 0x80649b8
  y = "fun",
  x = "test"
}
lua_debug> cont
如果我們在第 8 行之後新增 stop"it",我們可以在函數 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 · 偏好設定
編輯 · 歷史記錄
最近編輯時間為 2006 年 12 月 31 日上午 12:04 GMT (差異)