Skip to content

Instantly share code, notes, and snippets.

@pinealservo
Forked from creationix/coro.lua
Created June 24, 2012 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinealservo/2981028 to your computer and use it in GitHub Desktop.
Save pinealservo/2981028 to your computer and use it in GitHub Desktop.
luvit coro sugar idea
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."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment