fork download
  1. print( 'coroutine test' )
  2.  
  3. JobType = { Update=1, Draw=2, GetScore=3 }
  4.  
  5. -- GameObjectへのresumeを適切に処理するためのYieldのラップ関数です。
  6. -- resumeの引数に応じた処理を行います。
  7. -- resumeの引数がJobType.Updateでない場合は、必要な処理を行ったあとすぐに再びyieldを行います。( つまりGameObjectコルーチンの実行位置は変わらない )
  8. function GameObjectYield( drawFunc, getScoreFunc )
  9. local result = {}
  10. repeat
  11. local jobType = coroutine.yield( result )
  12. result = {}
  13. if jobType == JobType.Draw then
  14. drawFunc()
  15. elseif jobType == JobType.GetScore then
  16. result.Score = getScoreFunc and getScoreFunc()
  17. end
  18. until jobType == JobType.Update
  19. end
  20.  
  21. -- ゲームのメインロジックを表すコルーチンです。
  22. function GameObject()
  23.  
  24. GameObjectYield( function() print"State : FadeIn" end )
  25.  
  26. local gameTime = 0
  27. local score = 0
  28. while true do
  29. if gameTime == 3 then
  30. break
  31. end
  32. score = score + math.random( 1000 )
  33. GameObjectYield( function() print("State : Game / "..gameTime) end, function() return score end )
  34.  
  35. gameTime = gameTime + 1
  36. end
  37.  
  38. GameObjectYield( function() print"State : FadeOut" end )
  39. end
  40.  
  41. GameObjectCoroutine = coroutine.create( GameObject )
  42.  
  43. -- スコアを表示するためのコルーチンです。resumeが呼ばれるたびに表示するスコアが実際のスコアに近づいていきます。
  44. function ScoreDrawer()
  45. local drawScore = 0
  46. while true do
  47. local result, retT = coroutine.resume( GameObjectCoroutine, JobType.GetScore )
  48. local currentScore = retT.Score
  49. if currentScore ~= nil then
  50. if currentScore > drawScore then drawScore = drawScore + 1
  51. elseif currentScore < drawScore then drawScore = drawScore - 1
  52. end
  53. print( 'ScoreDrawer : '..drawScore..'('..currentScore..')' )
  54. end
  55. coroutine.yield()
  56. end
  57. end
  58. ScoreDrawerCoroutine = coroutine.create( ScoreDrawer )
  59.  
  60. function Update()
  61. if coroutine.status( GameObjectCoroutine ) == "suspended" then
  62. coroutine.resume( GameObjectCoroutine, JobType.Update )
  63. end
  64. end
  65.  
  66. function Draw()
  67. if coroutine.status( GameObjectCoroutine ) == "suspended" then
  68. coroutine.resume( GameObjectCoroutine, JobType.Draw )
  69. end
  70. -- print( 'ScoreDrawerCoroutine : '..coroutine.status( ScoreDrawerCoroutine ) )
  71. result, mes = coroutine.resume( ScoreDrawerCoroutine )
  72. if result == false then
  73. print( mes )
  74. end
  75. end
  76.  
  77. function Framework()
  78. for i=1, 5 do
  79. Update()
  80. Draw()
  81. end
  82. end
  83.  
  84. Framework()
Success #stdin #stdout 0.02s 2496KB
stdin
Standard input is empty
stdout
coroutine test
State : FadeIn
State : Game / 0
ScoreDrawer : 1(841)
State : Game / 1
ScoreDrawer : 2(1236)
State : Game / 2
ScoreDrawer : 3(2020)
State : FadeOut