SHARE
TWEET

scope

a guest Jun 25th, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function scope(self)
  2.     local result
  3.     self=self or {}
  4.     self.list={}
  5.     self.error=self.error or error
  6.     local function auto(arg,close,msg)
  7.         if arg then
  8.             table.insert(self.list,{ arg=arg, fn=close or io.close })
  9.         else
  10.             self.error(msg or "init error",2)
  11.         end
  12.         return arg
  13.     end
  14.     if self.init then self.init(auto) end
  15.     local ok,err=pcall(function() result=table.pack(self.body()) end)
  16.     if self.done then self.done(ok,err) end
  17.     for _,close in pairs(self.list) do close.fn(close.arg) end
  18.     if not ok then self.error(err) end
  19.     return table.unpack(result)
  20. end
  21.  
  22.  
  23. function test()
  24.     local src,dst
  25.     scope {
  26.         init=function(auto)
  27.             src=auto(io.open("file1.txt","w"))
  28.             dst=auto(io.open("file2.txt","w"),function(f) print "close file" f:close() end )
  29.         end,
  30.         body=function()
  31.             src:write "hello"
  32.             dst:write "world"
  33.         end,
  34.     }
  35. end
  36.  
  37. test()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top