Last active
July 29, 2019 02:28
-
-
Save evilstreak/5517087 to your computer and use it in GitHub Desktop.
Event Streams in Lua
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
function double( x ) | |
return x * 2; | |
end | |
function square( x ) | |
return x * x; | |
end | |
s = EventStream.new(); | |
t = s:map( double ); | |
t:listen( function( ... ) print( "t", ... ) end ); | |
u = t:map( square ); | |
u:listen( function( ... ) print( "u", ... ) end ); | |
s:emit( 3 ); | |
-- prints: | |
-- t 6 | |
-- u 36 | |
t:emit( 4 ); | |
-- what should this print? | |
u:emit( 5 ); | |
-- what should this print? |
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
function add( x, y ) | |
return x + y; | |
end | |
function square( x ) | |
return x * x; | |
end | |
function is_odd( x ) | |
return x % 2 == 1; | |
end | |
s = EventStream.new(); | |
t = s:map( add ):filter( is_odd ); | |
t:listen( function( ... ) print( "t", ... ) end ); | |
u = s:map( add ):map( square ); | |
u:listen( function( ... ) print( "u", ... ) end ); | |
s:emit( 3, 4 ); | |
-- prints: | |
-- t 7 | |
-- u 49 | |
t:emit( 1, 3 ); | |
-- prints: | |
-- t 1 3 | |
-- should this instead print nothing? | |
u:emit( 2, 7 ); | |
-- prints: | |
-- u 2 7 | |
-- should this instead print 81? |
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 EventStream = {}; | |
function EventStream.new() | |
local object = { __listeners = {} }; | |
setmetatable( object, { __index = EventStream } ); | |
return object; | |
end | |
function EventStream:listen( listener ) | |
table.insert( self.__listeners, listener ); | |
end | |
function EventStream:emit( ... ) | |
for _, listener in ipairs( self.__listeners ) do | |
listener( ... ); | |
end | |
end | |
function EventStream:map( fn ) | |
local stream = EventStream:new(); | |
self:listen( function( ... ) | |
stream:emit( fn( ... ) ); | |
end ) | |
return stream; | |
end | |
function EventStream:filter( fn ) | |
local stream = EventStream:new(); | |
self:listen( function( ... ) | |
if fn( ... ) then | |
stream:emit( ... ); | |
end | |
end ) | |
return stream; | |
end | |
return EventStream; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment