1. ホーム
  2. スクリプト・コラム
  3. ルア

Luaプログラミングの例(7)。協調プログラムのための基本ロジック

2022-01-09 15:02:11
co=coroutine.create(function()
 print("hi")
end)
print(coroutine.status(co))
coroutine.resume(co)
print(coroutine.status(co))
print()

co=coroutine.create(function()
 for i=1,2 do
 print("co",i)
 coroutine.yield()
 end
end)
coroutine.resume(co)
print(coroutine.status(co))

coroutine.resume(co)
print(coroutine.status(co))

coroutine.resume(co) - no output
print(coroutine.status(co))
print()

co=coroutine.create(function(a,b,c)
 print("co",a,b,c)
end)
coroutine.resume(co,1,2,3)

co=coroutine.create(function(a,b)
 print("I'm before yield") --- first run execution
 coroutine.yield(a+b,a-b,"needless args") --Stop here and return the arguments to yield
 print("Mgs")
end)
print(coroutine.resume(co,20,10)) --Pass the arguments to yield, process them and return
print("I print first")
coroutine.resume(co)

co=coroutine.create(function()
 return "I'll return"
end)
print(coroutine.resume(co)) - the return value of the main function is passed back to resume
print()


出力結果です。

suspended
hi
dead

co 1
suspended
co 2
suspended
dead

co 1 2 3
I'm before yield
true 30 10 needless args
I print first
Mgs
true I'll return