Last active
August 18, 2017 06:19
-
-
Save zhoulifu/7619ea01bb42e402cb86b6765600c966 to your computer and use it in GitHub Desktop.
Lua snippet
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
--- http://www.lua.org/pil/9.html | |
function producer() | |
return coroutine.create( | |
function() | |
while true do | |
local v = io.read() | |
coroutine.yield(v) | |
if not v then break end | |
end | |
end) | |
end | |
function consumer(prod) | |
while true do | |
local state, v = coroutine.resume(prod) | |
if not v then break end | |
io.write(v, "\n") | |
end | |
end | |
p = producer() | |
consumer(p) |
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 fib_closure() | |
local a = 1 | |
local b = 1 | |
return function() | |
local v = a | |
a, b = b, b + v | |
return v | |
end | |
end | |
function fib_ite_expand () | |
local a = 1 | |
return function (_, b) | |
v, a = a, b | |
return (v + b), v | |
end, nil, 1 | |
end | |
function fib_stateless() | |
local state = {a = 1, b = 1} | |
return function (st) | |
v = st.a | |
st.a, st.b = st.b, st.b + v | |
return v | |
end, state | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment