Advertisement
Guest User

scope

a guest
Jun 30th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.68 KB | None | 0 0
  1. function scope(body)
  2.     local list,res={}
  3.     local function auto(close,msg)
  4.         return function(t)
  5.             if type(t)~='table' then error("need table: { expression }",2) end
  6.             if t[1] then table.insert(list,{ arg=t[1], fn=close or io.close })
  7.             else
  8.                 if msg=='weak' then return table.unpack(t) end
  9.                 error(msg or t[2] or "no resource",2)
  10.             end
  11.             return table.unpack(t)
  12.         end
  13.     end
  14.     local function defer(fn) auto(fn){true} end
  15.     local ok,err=pcall(function() res={body(auto,defer)} end)
  16.     for i=#list,1,-1 do list[i].fn(list[i].arg) end
  17.     if not ok then
  18.         if type(err)~='string' then error(err,2)
  19.         else error("scope error\nlua: "..err,2) end
  20.     end
  21.     return table.unpack(res)
  22. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement