改造Lua的debug.traceback(),让其显示栈上所有的局部变量

function tracebackex()  
local ret = ""  
local level = 2  
ret = ret .. "stack traceback:\n"  
while true do  
   --get stack info  
   local info = debug.getinfo(level, "Sln")  
   if not info then break end  
   if info.what == "C" then                -- C function  
    ret = ret .. tostring(level) .. "\tC function\n"  
   else           -- Lua function  
    ret = ret .. string.format("\t[%s]:%d in function `%s`\n", info.short_src, info.currentline, info.name or "")  
   end  
   --get local vars  
   local i = 1  
   while true do  
    local name, value = debug.getlocal(level, i)  
    if not name then break end  
    ret = ret .. "\t\t" .. name .. " =\t" .. tostringex(value, 3) .. "\n"  
    i = i + 1  
   end    
   level = level + 1  
end  
return ret  
end  
  
function tostringex(v, len)  
if len == nil then len = 0 end  
local pre = string.rep('\t', len)  
local ret = ""  
if type(v) == "table" then  
   if len > 5 then return "\t{ ... }" end  
   local t = ""  
   for k, v1 in pairs(v) do  
    t = t .. "\n\t" .. pre .. tostring(k) .. ":"  
    t = t .. tostringex(v1, len + 1)  
   end  
   if t == "" then  
    ret = ret .. pre .. "{ }\t(" .. tostring(v) .. ")"  
   else  
    if len > 0 then  
     ret = ret .. "\t(" .. tostring(v) .. ")\n"  
    end  
    ret = ret .. pre .. "{" .. t .. "\n" .. pre .. "}"  
   end  
else  
   ret = ret .. pre .. tostring(v) .. "\t(" .. type(v) .. ")"  
end  
return ret  
end  


 

你可能感兴趣的:(Lua,lua,function,table,c)