What are Lua coroutines even for? Why doesn't this code work as I expect it?

后端 未结 3 348
孤街浪徒
孤街浪徒 2020-12-23 20:37

I\'m having trouble understanding this code... I was expecting something similar to threading where I would get an output with random \"nooo\" and \"yaaaay\"s interspersed w

3条回答
  •  醉梦人生
    2020-12-23 21:26

    Coroutines aren't threads.

    Coroutines are like threads that are never actively scheduled. So yes you are kinda correct that you would have to write you own scheduler to have both coroutines run simultaneously.

    However you are missing the bigger picture when it comes to coroutines. Check out wikipedia's list of coroutine uses. Here is one concrete example that might guide you in the right direction.

    -- level script
    -- a volcano erupts every 2 minutes
    function level_with_volcano( interface )
    
       while true do
          wait(seconds(5))
          start_eruption_volcano()
          wait(frames(10))
          s = play("rumble_sound")
          wait( end_of(s) )
          start_camera_shake()
    
          -- more stuff
    
          wait(minutes(2))
        end
    
    
    end
    

    The above script could be written to run iteratively with a switch statement and some clever state variables. But it is much more clear when written as a coroutine. The above script could be a thread but do you really need to dedicate a kernel thread to this simple code. A busy game level could have 100's of these coroutines running without impacting performance. However if each of these were a thread you might get away with 20-30 before performance started to suffer.

    A coroutine is meant to allow me to write code that stores state on the stack so that I can stop running it for a while (the wait functions) and start it again where I left off.

提交回复
热议问题