Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function scope(self)
- local result
- self=self or {}
- self.list={}
- self.error=self.error or error
- local function auto(arg,close,msg)
- if arg then
- table.insert(self.list,{ arg=arg, fn=close or io.close })
- else
- self.error(msg or "init error",2)
- end
- return arg
- end
- if self.init then self.init(auto) end
- local ok,err=pcall(function() result=table.pack(self.body()) end)
- if self.done then self.done(ok,err) end
- for _,close in pairs(self.list) do close.fn(close.arg) end
- if not ok then self.error(err) end
- return table.unpack(result)
- end
- function test()
- local src,dst
- scope {
- init=function(auto)
- src=auto(io.open("file1.txt","w"))
- dst=auto(io.open("file2.txt","w"),function(f) print "close file" f:close() end )
- end,
- body=function()
- src:write "hello"
- dst:write "world"
- end,
- }
- end
- test()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement