前言
Lua 標準庫 debug 提供底層除錯原語:堆疊追蹤、函數資訊、上值存取、掛鉤。雖無內建互動式除錯器,但生態圈有豐富的命令列與圖形化工具。本文系統解析 debug 庫核心 API、實戰除錯技巧、主流除錯器對比與選型建議。
核心 API 速查
| 函數 | 用途 |
debug.traceback([thread,] [message,] [level]) | 返回堆疊追蹤字串 |
debug.getinfo([thread,] function/level, [what]) | 返回函數資訊表 (name, source, linedefined, currentline, nups, ...) |
debug.getlocal([thread,] level, local) | 取得區域變數名/值 |
debug.setlocal([thread,] level, local, value) | 設定區域變數值 |
debug.getupvalue(func, n) | 取得閉包第 n 個上值名/值 |
debug.setupvalue(func, n, value) | 設定閉包第 n 個上值值 |
debug.sethook([thread,] hook, mask, [count]) | 設定掛鉤 (call/return/line/count) |
debug.gethook([thread]) | 取得當前掛鉤 |
debug.getregistry() | 返回註冊表 (C API 常用) |
debug.getmetatable/value/setmetatable | 元表操作 (5.1+ 已有全域同名函數) |
實戰範例一:堆疊追蹤與函數資訊
function myfunc()
print(debug.traceback("Stack trace"))
print(debug.getinfo(1)) -- 當前函數資訊
print("Stack trace end")
return 10
end
myfunc()
-- 輸出:
-- Stack trace
-- stack traceback:
-- test.lua:2: in function 'myfunc'
-- test.lua:8: in main chunk
-- [C]: ?
-- table: 0x...
-- Stack trace end
實戰範例二:上值檢查與熱修改 (閉包內部狀態)
function newCounter()
local n = 0
local k = 0
return function()
k = n
n = n + 1
return n
end
end
local counter = newCounter()
print(counter()) -- 1
print(counter()) -- 2
-- 檢查上值
local i = 1
repeat
local name, val = debug.getupvalue(counter, i)
if name then
print("index", i, name, "=", val)
if name == "n" then
debug.setupvalue(counter, i, 10) -- 熱修改 n = 10
end
i = i + 1
end
until not name
print(counter()) -- 11 (原本應為 3)
除錯器分類與推薦
命令列除錯器
| 工具 | 特色 | 支援版本 |
| RemDebug | 遠端除錯、斷點、狀態檢視、CGILua 支援 | Lua 5.0/5.1 |
| clidebugger | 純 Lua 實作、零依賴、單檔案 | Lua 5.1 |
| ctrace | C API 呼叫追蹤 | — |
| xdbLua | Windows 專用命令列 | — |
| LuaInterface Debugger | .NET 整合、事件驅動 | — |
| Rldb | Socket 遠端、跨平台、功能最全 | Windows/Linux |
| ModDebug | 遠端控制、斷點、狀態檢視 | — |
圖形化除錯器 (IDE 整合)
| 工具 | 特色 | 平台 |
| SciTE | Windows 官方 IDE 內建、斷點、單步、變數檢視 | Windows |
| Decoda | 遠端除錯、商業授權 | Windows |
| ZeroBrane Studio | 推薦:開源、跨平台、遠端除錯、堆疊/表視圖、靜態分析、支援 LuaJIT/Love2D/Moai | Windows/macOS/Linux |
| akdebugger | Eclipse 外掛 | 跨平台 |
| luaedit | 遠端/本地除錯、語法高亮、自動完成、斷點管理 | Windows |
進階技巧
- 條件斷點模擬:在掛鉤函數中判斷條件滿足才
debug.debug() 進入互動模式。
- 效能分析:
debug.sethook(func, "", 100000) 每 10 萬條指令採樣,統計熱點函數。
- 遠端除錯流程:目標機啟動
RemDebug / MobDebug 監聽埠,IDE 連線下發斷點、檢視變數。
- OpenResty/ngx_lua 除錯:使用
mobdebug + ZeroBrane Studio,支援 Nginx worker 進程除錯。
- 生產環境安全:嚴禁生產環境載入
debug 庫 (效能損耗、安全風險),以 lua_code_cache off 僅開發環境開啟。
總結
Lua debug 庫提供「機制而非策略」的底層原語,配合 ZeroBrane Studio 等現代 IDE,可獲得接近靜態語言的除錯體驗。核心技能:traceback 定位錯誤、getinfo 理解執行上下文、getupvalue/setupvalue 熱修改閉包狀態、sethook 實現分析器/條件斷點。記住:開發環境全開、生產環境嚴禁。