Advertisement
Guest User

errortest.lua

a guest
Aug 8th, 2018
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.72 KB | None | 0 0
  1. function a()
  2.     print("A!")
  3.     sleep(1)
  4.     b()
  5. end
  6. function b()
  7.     print("B!")
  8.     error("Error in B!")
  9. end
  10.  
  11. -- here be dragons
  12. local function buildStackTrace(rootErr)
  13.     local trace = {}
  14.     local i, hitEnd, _, e = 4, false
  15.  
  16.     repeat
  17.         _, e = pcall(function() error("<tracemarker>", i) end)
  18.         i = i + 1
  19.         if e == "xpcall: <tracemarker>" or e == "pcall: <tracemarker>" then
  20.             hitEnd = true
  21.             break
  22.         end
  23.         table.insert(trace, e)
  24.     until i > 10
  25.  
  26.     table.remove(trace)
  27.     table.remove(trace, 1)
  28.  
  29.     if rootErr:match("^" .. trace[1]:match("^(.-:%d+)")) then table.remove(trace, 1) end
  30.  
  31.     local out = {}
  32.  
  33.     table.insert(out, rootErr)
  34.    
  35.     for i, v in ipairs(trace) do
  36.         table.insert(out, "  at " .. v:match("^(.-:%d+)"))
  37.     end
  38.  
  39.     if not hitEnd then
  40.         table.insert(out, "  ...")
  41.     end
  42.  
  43.     return table.concat(out, "\n")
  44. end
  45.  
  46. local env = setmetatable({}, {__index=_ENV}) -- No need to override the runnign program
  47.  
  48.     env.pcall = function(f, ...)
  49.         local args = { ... }
  50.         return xpcall(function() f(unpack(args)) end, buildStackTrace)
  51.     end
  52.  
  53.     env.xpcall = function(f, e)
  54.         return xpcall(function() f() end, function(err) e(buildStackTrace(err)) end)
  55.     end
  56.  
  57. local f = setfenv(a, env)
  58.  
  59. local function wrapper(func, args)
  60.     local stack
  61.     xpcall(function() func(unpack(args)) end,
  62.     function(err)
  63.         stack = buildStackTrace(err)
  64.     end
  65.     )
  66.     if stack then error(stack, 0) end
  67.     return true
  68. end
  69.  
  70. local co = coroutine.create(wrapper)
  71. local ok, next = coroutine.resume(co, f, {})
  72.  
  73. print(next)
  74.  
  75. while ok and coroutine.status(co) ~= "dead" do
  76.     e = {os.pullEvent()}
  77.     if not next or e[1] == next or next == "" then
  78.         ok, next = coroutine.resume(co, unpack(e))
  79.     end
  80. end
  81.  
  82. if not ok then
  83.     printError(next)
  84. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement