Advertisement
Guest User

pure

a guest
Jul 4th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.97 KB | None | 0 0
  1. function pure(body,env)
  2.     return assert(load("return function(_ENV) return "..body.." end"))
  3.     ()(env or {})
  4. end
  5. --
  6. -- x=1
  7. -- local y=2
  8. -- fn=pure[[function(print)
  9. --   x=10
  10. --   y=20
  11. --   print(x,y)
  12. -- end]]
  13. -- fn(print)
  14. -- print(x,y)
  15.  
  16. function isolated(s)
  17.     if type(s)=="string" then return pure(s) end
  18.     return function(body) return pure(body,s) end
  19. end
  20. --
  21. -- x=1 fn=isolated{x=10,print=print}[[ function() print(x) end ]] fn(print) print(x)
  22.  
  23. function pure_check()
  24.     local i,r,n,v,f
  25.     i=0 r={} f=debug.getinfo(2,"f").func
  26.     while true do
  27.         i=i+1 n,v=debug.getupvalue(f,i)
  28.         if n==nil then break end
  29.         if n~="_ENV" then table.insert(r,n) end
  30.     end
  31.     if #r>0 then
  32.         error("pure_check fail: you must define\n\tlocal "..table.concat(r,","),2)
  33.     end
  34. end
  35. --[[
  36. global_a="global_a"
  37. local upvalue_a="upvalue_a"
  38. function test(v1) pure_check() local _ENV={G=_G}
  39.     -- local upvalue_a
  40.     upvalue_a="local_a"
  41.     local z=upvalue_a..v1
  42.     G.print(z,G.global_a)
  43. end
  44. test "error"
  45. ]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement