Lua學習筆記--迭代器和協程(二)

壹頁書發表於2015-11-30
迭代器
function iterator(tab)
        local i=0 
        return  function() 
                i=i+1;
                return tab[i]
                end 
end 

t={10,20,30}
it=iterator(t)
while true do  
        local element=it()
        if element==nil then break end 
        print(element)
end


--另外一種呼叫方式
for element in iterator(t) do
        print(element)
end

協程
--相當於建立了Runnable物件
co=coroutine.create(
                function()
                print("hello world")
                end 
)
--物件建立之後,協程的狀態是掛起,並沒有執行
print(coroutine.status(co))
--執行程式.
coroutine.resume(co)

已經執行完成的協程,是死亡狀態,不能再次執行.
但是yield可以將程式由執行狀態,轉為掛起狀態.

co=coroutine.create(
                function()
                        for i=1,3 do
                        print("co",i)
                        coroutine.yield()
                        end 
                end 
)

print(coroutine.status(co))
coroutine.resume(co)
print(coroutine.status(co))
coroutine.resume(co)
coroutine.resume(co)

[nginx@localhost~]$./lua_test.lua 
suspended
co 1
suspended
co 2
co 3

管道
function receive()
        local status,value=coroutine.resume(producer)
        print("receive:"..value)
        return value
end

function send(x)
        print("send:"..x)
        coroutine.yield(x)
end

producer=coroutine.create(
function()
        while true do
                local x=io.read()
                send(x)
        end 
end
)

consumter=coroutine.create(
function()
        while true do
                local x=receive()
                io.write(x,"\n")
        end 
end
)

coroutine.resume(consumter)


過濾器

function receive(prod)
    local status,value=coroutine.resume(prod)
    return value
end

function send(x)
    coroutine.yield(x)
end

function producer()
    return 
        coroutine.create(
        function()
            while true do
                local x=io.read()
                send(x)
            end
        end
        )
end

function filter(prod)
    return coroutine.create(function()
        for line=1,math.huge do
            local x=receive(prod)
            x=string.format("%5d: %s",line,x)
            send(x)
        end
    end
    )
end

function consumter(prod)
    while true do
        local x=receive(prod)
        io.write(x,"\n")
    end
end

p=producer()
f=filter(p)
consumter(f)


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1850026/,如需轉載,請註明出處,否則將追究法律責任。

相關文章