Skip to content

Instantly share code, notes, and snippets.

@pkulchenko
Forked from marcoonroad/lazylists.lua
Created April 29, 2021 05:14
Show Gist options
  • Save pkulchenko/72b560135d0e4f11f958e756affe49e4 to your computer and use it in GitHub Desktop.
Save pkulchenko/72b560135d0e4f11f958e756affe49e4 to your computer and use it in GitHub Desktop.
Lazy evaluation on lists (a la Perl6) with Lua... [ FIXED ]
#!/usr/bin/lua
-- Perl6 example --
--[[
my @xs := gather {
my $x = 0;
my $y = 1;
while True {
take $x;
($x, $y) = ($y, $x + $y);
}
}
for @xs -> $x {
say $x;
sleep 1;
}
]]--
-- Lua version --
-- as like Perl 6 ':=" operator --
function bind (lambda)
local glue = {
-- lazy assignment --
__index = function (table, key)
if key > 0 then
local value
for index = 1, key do
if not rawget (table, index) then
value = lambda ( )
rawset (table, index, value)
end
end
return table[ key ]
end
end,
-- iterator --
__call = function (table)
local index = 0
return function ( )
index = index + 1
return table[ index ]
end
end
}
return setmetatable ({ }, glue)
end
-- short alias Perl6 like --
local gather = coroutine.wrap
local take = coroutine.yield
-- lazy assignment test --
-- fibonacci sequence --
local xs = bind (gather (function ( )
local x = 0
local y = 1
while true do
take (x)
x, y = y, x + y
end
end))
-- iterator test --
-- loop forever --
for x in xs( ) do
print (x)
os.execute "sleep 1"
end
-- end of script --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment