Using coroutine on Lua

The Lua documentation about coroutine is not much clear and the example is not much useful. Fortunately I found an explanation how to use it and simplify the idea here:

sleep_awhile = function (period)
        os.execute("sleep "..period)
        end

func_a = function()
        nnew = 0
        while true do
           nnew = nnew + 1
           print ("func_a ", nnew)
           coroutine.yield(nnew)
           print ("AGAIN ...")
        end
end

func_b = function()
        count = 0
        while true do
           count = count + 1
           print ("func_b ", count)
           coroutine.yield()
        end
end

-- ======= Main code =============

cor_a = coroutine.create(func_a)
cor_b = coroutine.create(func_b)

while true do
        itdidit,newcount = coroutine.resume(cor_a)
        sleep_awhile(1)
        print (newcount)
        itdidit = coroutine.resume(cor_b)
end

I hope it be useful for you too.

Source: http://www.wellho.net/resources/ex.php4?item=u114/ff2.lua

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s