| fx.lua | Rename to fx.lua | |
| LICENSE | make eff into a library | |
| main.lua | Rename to fx.lua | |
| README.md | Rename to fx.lua | |
fx.lua
fx.lua is a tiny effects handler library built over top of Lua coroutines.
local fx = require "fx"
local function coin_tossing()
for i = 1, 10 do
fx.do_fxect("log", fx.do_effect "flip")
end
end
fx.run (coin_tossing)
{ flip =
function(resume)
local randomness = math.random()
if randomness > 1/2 then
return resume("heads")
else
return resume("tails")
end
end
, log =
function(resume, message)
return resume(print(message))
end
}
Effect handlers provide a mechanism for deferring operations to external callback. This allows for different handlers to be swapped around without changing the logic of code using effects. This allows for powerful, flexible, and modular flow control mechanisms.
However, this library is more a demonstration than a practicle utility. Effect systems are more useful in statically typed languages that can track them.
Caveat
fx.lua has a few caveats to be aware of if the previous warning didn't dissuade you from using it:
-
This library assumes it has full control over Lua's coroutines. If an effectful function yields without calling
fx.do_effect(effect, [args]),fx.luawill have unpredictable behavior. Tho, it will likely just crash with a confusing error message and trace. -
resumeis recursive. Internally, it uses tail recursion. However, if a handler doesn't callresumein tail-call position (return resume(...)), it will slowly fill up the call stack each time it's used. I could probably trampoline this in some way, but that sounds hard. -
There is probably some other footgun here. If despite all this you found the library useful, let me know :)