diff options
author | Robin Haberkorn <robin.haberkorn@googlemail.com> | 2016-01-04 11:44:32 +0100 |
---|---|---|
committer | Robin Haberkorn <robin.haberkorn@googlemail.com> | 2016-01-04 11:44:32 +0100 |
commit | 86937cf26e87ad707aebeea202854fad6ab0073a (patch) | |
tree | 0af895dda6d89b4069e8056f39d8709761a8662b | |
parent | 65a97a2163e40019e911053fb1e50b22337af118 (diff) | |
download | applause2-86937cf26e87ad707aebeea202854fad6ab0073a.tar.gz |
added RepeatStream: allows you to repeat some stream for a number of times (or infinitely)
* this currently also works for very long streams without precalculating stuff
* On the other hand, after each iteration the target stream must be reinitialized.
This is not safe in generator functions (FIXME).
-rw-r--r-- | applause.lua | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/applause.lua b/applause.lua index a568a4a..d598a86 100644 --- a/applause.lua +++ b/applause.lua @@ -135,6 +135,10 @@ function Stream:sync() return SyncedStream:new(self) end +function Stream:rep(repeats) + return RepeatStream:new(self, repeats) +end + function Stream:map(fnc) return MapStream:new(self, fnc) end @@ -641,6 +645,35 @@ function ConcatStream:len() return len end +RepeatStream = DeriveClass(Stream, function(self, stream, repeats) + self.streams = {tostream(stream)} + self.repeats = repeats or math.huge +end) + +function RepeatStream:tick() + local i = 1 + local stream_tick = self.streams[1]:tick() + local repeats = self.repeats + + return function() + while i <= repeats do + local sample = stream_tick() + if sample then return sample end + + -- next iteration + i = i + 1 + -- FIXME: The tick() method itself may be too + -- inefficient for realtime purposes. + -- Also, we may slowly leak memory. + stream_tick = self.streams[1]:tick() + end + end +end + +function RepeatStream:len() + return self.streams[1]:len() * self.repeats +end + -- Ravel operation inspired by APL. -- This removes one level of nesting from nested streams -- (e.g. streams of streams), and is semantically similar |