Guest User

Untitled

a guest
Nov 17th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. local fs = require 'fs'
  2. local timer = require 'timer'
  3. local coroutine = require 'coroutine'
  4.  
  5. local function fiber(block, callback)
  6. local paused
  7. local co = coroutine.create(block)
  8. local function check(success, ...)
  9. if not success then
  10. return callback(...)
  11. end
  12. if not paused then
  13. return callback(nil, ...)
  14. end
  15. paused = false
  16. end
  17. local function async_wrap(fn)
  18. return function(...)
  19. local args = {...}
  20. args[#args + 1] = function (err, result)
  21. if err then
  22. check(coroutine.resume(co, false, err))
  23. else
  24. check(coroutine.resume(co, result))
  25. end
  26. end
  27. fn(unpack(args))
  28. paused = true
  29. return coroutine.yield()
  30. end
  31. end
  32. check(coroutine.resume(co, wait))
  33. end
  34.  
  35.  
  36. print "Starting fiber."
  37. fiber(function (async_wrap)
  38. local open = async_wrap(fs.open)
  39. local sleep = async_wrap(timer.setTimeout)
  40.  
  41. print "Opening file"
  42. local fd = assert(open(__dirname .. "/../LICENSE.txt", "r", "0644"))
  43. print("file opened at " .. fd)
  44. sleep(1000)
  45. error("Oops")
  46. return 5,6
  47.  
  48. end, function (err, ...)
  49. p({err=err,...})
  50. if err then error(err) end
  51. print "Fiber finished"
  52. end)
  53. print "started."
Add Comment
Please, Sign In to add comment