Skip to content

Instantly share code, notes, and snippets.

@chromy
Last active November 13, 2020 08:40
Show Gist options
  • Save chromy/6001722 to your computer and use it in GitHub Desktop.
Save chromy/6001722 to your computer and use it in GitHub Desktop.
Python yield syntax in Lua by abusing coroutines.
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
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
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
@FoxieFlakey
Copy link

abusing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment