为什么Lua直接返回函数结果无法正确调试?

我正在尝试编写一个调试器函数,可以显示出出错发生的确切行数、函数名和定义函数的行数。考虑以下代码:

function StatusLog(vet,vErr)
  local tInfo, sDbg = debug.getinfo(2), ""
  sDbg = sDbg.." "..(tInfo.linedefined and "["..tInfo.linedefined.."]" or "X")
  sDbg = sDbg..(tInfo.name and tInfo.name or "Main")
  sDbg = sDbg..(tInfo.currentline and ("["..tInfo.currentline.."]") or "X")
  sDbg = sDbg.."@"..(tInfo.source and (tInfo.source:gsub("^%W", "")) or "N")
  print("调试信息:"..sDbg)
  return vRet
end

local function add(a,b)
  if(not a) then return StatusLog(nil, "缺少参数A") end
  if(not b) then
    StatusLog(nil, "缺少参数B")
    return nil
  end
  return (a + b)
end

print(add(1,   1)) --- 输出:“2” 正常
print(add(1, nil)) --- 错误:[11]add[14] 正常
print(add(nil, 1)) --- 错误:[0]Main[21] 错误

很明显,当两个参数中有一个是nil时,函数add(a,b)会生成一个错误。然而,当参数B缺失时,调试信息正确,而当参数A缺失时,调试信息有点不正确。它必须显示与B相同的调试信息,但是却没有。这可能是由于return StatusLog语句导致堆栈出问题。

当我使用参数A的错误处理方法时,如何提取正确的调试信息,如函数名、定义的行数和错误行数?

点赞