-
-
Save pinealservo/2981028 to your computer and use it in GitHub Desktop.
luvit coro sugar idea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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