Skip to content

Instantly share code, notes, and snippets.

@Nymphium
Created July 6, 2019 19:17
Show Gist options
  • Save Nymphium/b495fc2792ece41b1c2a325dcdc3c43c to your computer and use it in GitHub Desktop.
Save Nymphium/b495fc2792ece41b1c2a325dcdc3c43c to your computer and use it in GitHub Desktop.
local eff = require('eff')
local inst, perform, handlers = eff.inst, eff.perform, eff.handlers
local Defer = inst()
local runDefer = function(th)
local tasks = {}
return handlers{
function(x)
for i = #tasks, 1, -1 do
tasks[i]()
end
return x
end,
[Defer] = function(k, task)
table.insert(tasks, task)
return k()
end
}(th)
end
local Close = inst()
local closer = function(resr, clos)
local close = function()
clos(resr)
end
return setmetatable({ resource = resr, close = close }, {__index = resr})
end
local close = function(resr, clos)
return perform(Close(closer(resr, clos)))
end
local runClose = function(th)
local h = handlers{
function(x) return x end,
[Close] = function(k, res)
perform(Defer(function() return res.close() end))
return k(res.resource)
end,
}
return runDefer(function()
return h(th)
end)
end
---
runClose(function()
local fileBuf = close(io.open("src.txt"), io.close)
local fileWriter = close(io.open("dst.txt", "a+"), io.close)
for line in fileBuf:lines() do
print(line)
fileWriter:write("> " .. line .. "\n")
end
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment