print( 'coroutine test' )
JobType = { Update=1, Draw=2, GetScore=3 }
-- GameObjectへのresumeを適切に処理するためのYieldのラップ関数です。
-- resumeの引数に応じた処理を行います。
-- resumeの引数がJobType.Updateでない場合は、必要な処理を行ったあとすぐに再びyieldを行います。( つまりGameObjectコルーチンの実行位置は変わらない )
function GameObjectYield( drawFunc, getScoreFunc )
local result = {}
repeat
local jobType = coroutine.yield( result )
result = {}
if jobType == JobType.Draw then
drawFunc()
elseif jobType == JobType.GetScore then
result.Score = getScoreFunc and getScoreFunc()
end
until jobType == JobType.Update
end
-- ゲームのメインロジックを表すコルーチンです。
function GameObject()
GameObjectYield( function() print"State : FadeIn" end )
local gameTime = 0
local score = 0
while true do
if gameTime == 3 then
break
end
score = score + math.random( 1000 )
GameObjectYield( function() print("State : Game / "..gameTime) end, function() return score end )
gameTime = gameTime + 1
end
GameObjectYield( function() print"State : FadeOut" end )
end
GameObjectCoroutine = coroutine.create( GameObject )
-- スコアを表示するためのコルーチンです。resumeが呼ばれるたびに表示するスコアが実際のスコアに近づいていきます。
function ScoreDrawer()
local drawScore = 0
while true do
local result, retT = coroutine.resume( GameObjectCoroutine, JobType.GetScore )
local currentScore = retT.Score
if currentScore ~= nil then
if currentScore > drawScore then drawScore = drawScore + 1
elseif currentScore < drawScore then drawScore = drawScore - 1
end
print( 'ScoreDrawer : '..drawScore..'('..currentScore..')' )
end
coroutine.yield()
end
end
ScoreDrawerCoroutine = coroutine.create( ScoreDrawer )
function Update()
if coroutine.status( GameObjectCoroutine ) == "suspended" then
coroutine.resume( GameObjectCoroutine, JobType.Update )
end
end
function Draw()
if coroutine.status( GameObjectCoroutine ) == "suspended" then
coroutine.resume( GameObjectCoroutine, JobType.Draw )
end
-- print( 'ScoreDrawerCoroutine : '..coroutine.status( ScoreDrawerCoroutine ) )
result, mes = coroutine.resume( ScoreDrawerCoroutine )
if result == false then
print( mes )
end
end
function Framework()
for i=1, 5 do
Update()
Draw()
end
end
Framework()