SHARE
TWEET

scope

a guest Jun 25th, 2019 64 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.     local ok,err=true
  15.     if self.init then ok,err=pcall(function() self.init(auto) end) end
  16.     if ok then ok,err=pcall(function() result=table.pack(self.body()) end) end
  17.     if self.done then self.done(ok,err) end
  18.     for _,close in pairs(self.list) do close.fn(close.arg) end
  19.     if not ok then self.error(err) end
  20.     return table.unpack(result)
  21. end
  22.  
  23.  
  24. function test()
  25.     local src,dst
  26.     scope {
  27.         init=function(auto)
  28.             dst=auto(io.open("file2.txt","w"),function(f) print "close file" f:close() end )
  29.             src=auto(io.open("file1.txt","w"))
  30.         end,
  31.         body=function()
  32.             src:write "hello"
  33.             dst:write "world"
  34.         end,
  35.     }
  36. end
  37.  
  38. 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