I've been wondering whether it was possible to implement deferred execution, .NET Linq-style, in Lua, just for funsies.
In .NET, we can create a sequence of elements known as an IEnumerable
. These elements can then be filtered through various means, such as map/reduce (Select(predicate)
, Where(predicate)
), but the computation for these filters are only executed when you enumerate over the IEnumerable - it is deferred.
I've been trying to implement a similar functionality in Lua, although I'm pretty rusty with Lua and haven't touched it for a while. I'd like to avoid using libraries that already do this for me as I'd like to be able to do it in pure Lua where possible.
My idea was that perhaps it would be possible using coroutines..
Enumerable = {
-- Create an iterator and utilize it to iterate
-- over the Enumerable. This should be called from
-- a "for" loop.
each = function(self)
local itr = Enumerable.iterator(self)
while coroutine.status(itr) ~= 'dead' do
return function()
success, yield = coroutine.resume(itr)
if success then
return yield
else
error(1, "error while enumerating")
end
end
end
end,
-- Return an iterator that can be used to iterate
-- over the elements in this collection.
iterator = function(self)
return coroutine.create(function()
for i = 1, #self do
coroutine.yield(self[i])
end
end)
end
}
tbl = {1, 2, 3}
for element in Enumerable.each(tbl) do
print(element)
end
table.insert(tbl, 4)
for element in Enumerable.each(tbl) do
print(element)
end
However, after writing this I realized this isn't really deferred execution.. this is just glorified iterators using green threads.
I'm trying to implement it to get a better understanding on how functional programming works, in a language that I am already aware of.
Thoughts?