Why Lua direct returning function result cannot be debugged properly?

103 Views Asked by At

I am trying to do a debugger function, which shows me the exact line the error happens, the function name it happened in and the line where the function is defined. Consider the following code:

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("Debug: "..sDbg)
  return vRet
end

local function add(a,b)
  if(not a) then return StatusLog(nil, "Missing argument A") end
  if(not b) then
    StatusLog(nil, "Missing argument B")
    return nil
  end
  return (a + b)
end

print(add(1,   1)) --- Prints: "2" Normal  OK
print(add(1, nil)) --- Errors: [11]add[14] OK
print(add(nil, 1)) --- Errors: [0]Main[21] KO

You can clearly see when either of the two arguments is nil the function add(a,b) will generate an error, however, when argument B is missing, the debug information is OK and when argument A is missing the debug information is kinda broken. It must show the same debug information as B, but it does not. It is maybe due to the return StatusLog statement, which breaks the stack.

How can extract the proper debugging information as the function name, the line defined and the line of the error when I'm using the error handling method for argument A?

0

There are 0 best solutions below