Last active
November 13, 2020 08:40
-
-
Save chromy/6001722 to your computer and use it in GitHub Desktop.
Python yield syntax in Lua by abusing coroutines.
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 make_iter(f) | |
return function(...) | |
local args = ... | |
local co = coroutine.create(f) | |
return function() | |
if coroutine.status(co) == "dead" then | |
return nil | |
end | |
_, result = coroutine.resume(co, args) | |
return result | |
end | |
end | |
end | |
local unique = make_iter(function(alist) | |
local seen = {} | |
for _, x in ipairs(alist) do | |
if not seen[x] then | |
yield(x) | |
seen[x] = true | |
end | |
end | |
end) | |
for x in unique({1, 1, 2, 3, 2}) do | |
print(x) | |
end |
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 unique = function(alist) | |
local seen = {} | |
return function(last) | |
local last, x | |
repeat | |
last, x = next(alist, last) | |
until x == nil or not seen[x] | |
if x == nil then | |
return nil | |
else | |
seen[x] = true | |
return x | |
end | |
end | |
end |
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
def unique(alist): | |
seen = set() | |
for x in alist: | |
if x not in seen: | |
yield x | |
seen.add(x) | |
for x in unique([1, 1, 2, 3, 2]): | |
print x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
abusing?