Search code examples
pythonpython-3.xluacoroutineequivalent

Python equivalent of Lua coroutines?


I've been working on a brick-stacking game in Lua. The core game code uses coroutines in the main game loop, to wait for events such as an input press, or a timer finishing. I'm considering switching it over to Python, to make it much more portable, but I can't figure out how to use async and await properly, to be equivalent to Lua's coroutines.

The following code is a simple coroutine example in Lua. How would I go about writing the same in Python, while behaving the same?

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)

Expected output:

10
24
1920

Solution

  • It's actually very similar:

    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