Advertisement
Guest User

scope

a guest
Jun 25th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.74 KB | None | 0 0
  1. function scope(body)
  2.     local list,res={}
  3.     local function auto(close,msg)
  4.         return function(t)
  5.             if t[1] then table.insert(list,{ arg=t[1], fn=close or io.close })
  6.             else error(t[2] or "no resource",2) end
  7.             return table.unpack(t)
  8.         end
  9.     end
  10.     local ok,err=pcall(function() res=table.pack(body(auto)) end)
  11.     for i=#list,1,-1 do list[i].fn(list[i].arg) end
  12.     if not ok then
  13.         if type(err)~='string' then error(err,2)
  14.         else error("scope error\nlua: "..err,2) end
  15.     end
  16.     return table.unpack(res)
  17. end
  18.  
  19.  
  20. local f1,f2,f3
  21. scope(function(auto)
  22.     f1=auto(io.close){ io.open("test1.txt","w") }
  23.     f2=auto(io.close){ io.open("test2.txt","w") }
  24.     f3=auto(io.close){ io.open("test8.txt","r") }
  25.     f1:write "test"
  26.     --error"shit happens"
  27.     print "done"
  28. end)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement