John
John

Reputation: 3484

Question about the coroutine of lua: why the main thread doesn't continue to run when the other thread yield?

Why the main thread doesn't continue to run when the other thread yield?

You see there is no "hello world" on the terminal.

function foo ()
    print("foo" )
    count = 0;
    while( 0<1 )
    do
       count = count + 1;
       print("count=", count);
       if count>5 then
         break
       end
    end

    return coroutine.yield()
  end
  
  co = coroutine.create(function ()
        foo();
        print("hello world")  --why doesn't "hello world" output to the terminal?
        print(type(co))
        return b, "end"
  end)

  coroutine.resume(co)

ADDED: This code snippet(adding one line code) seems work,but I don't fully understand why.

function foo ()
    print("foo" )
    count = 0;
    while( 0<1 )
    do
       count = count + 1;
       print("count=", count);
       if count>5 then
         break
       end
    end

    return coroutine.yield()
  end
  
  co = coroutine.create(function ()
        foo();
        print("hello world")
        print(type(co))
        return b, "end"
  end)

  coroutine.resume(co)
  coroutine.resume(co)  --add this line

Upvotes: 0

Views: 445

Answers (1)

Piglet
Piglet

Reputation: 28950

There is no "hello world" in the console because the coroutine yields befor it is printed.

co = coroutine.create(function ()
        foo();  -- <-- coroutine.yield() inside! 
        print("hello world")
        print(type(co))
        return b, "end"
  end)

Your coroutine calls foo() befor print("hello world"). Inside foo you call coroutine.yield.

Therefor your single coroutine.resume returns and your program is done.

Adding a second coroutine.resume(co) will make co continue where it yielded and hence start from print("hello world")

Upvotes: 1

Related Questions