Python相当于Lua协程?

问题描述 投票:0回答:1

我一直在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
python python-3.x lua coroutine equivalent
1个回答
0
投票

实际上非常相似:

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
© www.soinside.com 2019 - 2024. All rights reserved.