Pinkishu

Untitled

Jul 20th, 2012
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.55 KB | None | 0 0
  1. local errorStack = {}
  2. local mFinally = nil
  3.  
  4. local patt = { { ".* attempt to call nil", "NIL_FUNCTION_EXCEPTION" } }
  5. function errorToException(err)
  6.   for k,v in pairs( patt ) do
  7.     if string.find( err, v[1] ) then return v[2] end
  8.   end
  9.   return "UNHANDLED_EXCEPTION"
  10. end
  11.  
  12. local function doFinally()
  13.   if mFinally == nil or mFinally == "" then return end
  14.   func,err = loadstring(mFinally)
  15.   if func == nil then error(err) end
  16.   setfenv(func,getfenv())
  17.   local myErrorStack = errorStack
  18.   local mmFinally = mFinally
  19.   errorStack = {}
  20.   mFinally = ""
  21.   if func then pcall(func) end
  22.   errorStack = myErrorStack
  23.   mFinally = mmFinally
  24. end
  25.  
  26. function sFinally(str)
  27.   mFinally = str
  28. end
  29.  
  30.  
  31. function try(str)
  32.   func,err = loadstring(str)
  33.   errorStack = {}
  34.   if func then
  35.     setfenv(func,getfenv())
  36.     local myErrorStack = errorStack
  37.     errorStack = {}
  38.     local arg = {pcall(func)}
  39.     errorStack = myErrorStack
  40.     local errVal = table.remove(arg,1)
  41.     if not errVal then
  42.       table.insert(errorStack,errorToException(arg[1]))
  43.     else
  44.       doFinally()
  45.     end
  46.    
  47.   else
  48.     table.insert(errorStack,errorToException(err))
  49.   end
  50. end
  51.  
  52. function catch(err, str)
  53.   if #errorStack == 0 then return end
  54.   local lErr = table.remove(errorStack)
  55.   if lErr == err then
  56.     func,err = loadstring(str)
  57.     if func == nil then doFinally() error(err) end
  58.     setfenv(func,getfenv())
  59.     local myErrorStack = errorStack
  60.     errorStack = {}
  61.     if func then
  62.       pcall(func)
  63.     end
  64.     errorStack = myErrorStack
  65.     doFinally()
  66.   end
  67. end
Advertisement
Add Comment
Please, Sign In to add comment