相当于Lua协程的Python



我一直在Lua开发一款积木游戏。核心游戏代码在主游戏循环中使用协同程序,以等待输入按键或计时器结束等事件。我正在考虑将其切换到Python,使其更具可移植性,但我不知道如何正确使用asyncawait,以等效于Lua的协同程序。

下面的代码是Lua中的一个简单的协同程序示例。我该如何在Python中写同样的东西,同时表现同样的东西?

function myCoroutine(arg1)
print(arg1)
local newValue = coroutine.yield(arg1 + 2)
print(newValue)
local lastValue = coroutine.yield(arg1 * newValue^2)
print(lastValue)

end

local co = coroutine.create(myCoroutine)
local success, yield1 = coroutine.resume(co, 10)
local success, yield2 = coroutine.resume(co, yield1 * 2)
coroutine.resume(co, yield2 / 3)

预期输出:

10
24
1920

它实际上非常相似:

def myCoroutine():
arg1 = (yield)
print(arg1)
newValue = (yield arg1 + 2)
print(newValue)
lastValue = (yield arg1 * newValue ** 2)
print(lastValue)
co = myCoroutine()
co.send(None) # "prime" the coroutine
try:
yield1 = co.send(10)
yield2 = co.send(yield1 * 2)
co.send(yield2 // 3)
except StopIteration:
pass

最新更新