lua是一个小巧高效的脚本语言,但是一直都没有一个好用的调试器,很多项目团队还是用最简单的加print打印调试信息办法做调试。
最近研究了一下lua的debug库,发现完全可以基于debug库开发一个类似gdb的调试工具,于是花几天时间实现了一个初步可用的版本。
闲话少说,先上代码
--[[*****************************************************************************
**** Author : tanjie(tanjiesymbol@gmail.com)
**** Date : 2013-07-01
**** Desc : this is a gdb-like debug tools for lua
**** Usage : 1.require("ldb")
2.ldb.ldb_open() --you will pause here for setting breakpoints
3.ldb.ldb() --set breakpoint anywhere you want to pause
4.b/bd/be/bl --add/disable/enable/list the breakpoints
5.p/print --print local or global variables
6.s/step --step into a function
7.n/next --step over a function
8.l/list --list ten lines around the current line
9.f/file --print the current file and line number
10.bt --print traceback
11.c/cont --continue
*****************************************************************************]]
module("ldb",package.seeall)
dbcmd = {
next=false,
trace=false,
last_cmd="",
bps={},
max=0,
status="",
stack_depth = 0;
script_name = "ldb.lua"
}
function Split(str, delim, maxNb)
if string.find(str, delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
function get_stack_depth()
local stack_lines = Split(debug.traceback(),"\n")
local depth = 0
for i=1,#stack_lines do
if string.find(stack_lines[i],dbcmd.script_name) == nil then
depth = depth + 1
end
end
return depth
end
fun