Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local fs = require 'fs'
- local timer = require 'timer'
- local coroutine = require 'coroutine'
- local function fiber(block, callback)
- local paused
- local co = coroutine.create(block)
- local function check(success, ...)
- if not success then
- return callback(...)
- end
- if not paused then
- return callback(nil, ...)
- end
- paused = false
- end
- local function async_wrap(fn)
- return function(...)
- local args = {...}
- args[#args + 1] = function (err, result)
- if err then
- check(coroutine.resume(co, false, err))
- else
- check(coroutine.resume(co, result))
- end
- end
- fn(unpack(args))
- paused = true
- return coroutine.yield()
- end
- end
- check(coroutine.resume(co, wait))
- end
- print "Starting fiber."
- fiber(function (async_wrap)
- local open = async_wrap(fs.open)
- local sleep = async_wrap(timer.setTimeout)
- print "Opening file"
- local fd = assert(open(__dirname .. "/../LICENSE.txt", "r", "0644"))
- print("file opened at " .. fd)
- sleep(1000)
- error("Oops")
- return 5,6
- end, function (err, ...)
- p({err=err,...})
- if err then error(err) end
- print "Fiber finished"
- end)
- print "started."
Add Comment
Please, Sign In to add comment