Nil Admirari
Nil Admirari

Reputation: 139

Lua: turn MPV's mp.command_native_async into a coroutine

mp.command_native_async allows one to call an external executable from an MPV script. It accepts a completion callback, which receives the results of the call.

The following attempt at coroutinization even works:

local function co_subprocess(...)
    local co = coroutine.running()
    mp.command_native_async({
        name = 'subprocess',
        args = { ... },
        playback_only = false,
        capture_stdout = true,
    }, function(...)
        coroutine.resume(co, ...) -- RESUME POINT
    end)
    return coroutine.yield() -- YIELD POINT
end

coroutine.wrap(function ()
    success, result, error = co_subprocess('echo', 'Hello from MPV')
    print('success = ', success)
    print('error = ', error)
    if result then
        print('status = ', result.status)
        print('stdout = ', result.stdout)
    end
end)()

but I have questions about its correctness. co_subprocess yields immediately after calling mp.command_native_async. Callback is called by MPV at some later unspecified time, and that callback resumes the coroutine.

  1. Are there any guarantees by Lua runtime or by MPV that the callback will be called only after the coroutine has yielded?
  2. If there are no such guarantees, what's gonna happen if someone tries to resume a coroutine that haven't yielded?

Upvotes: 0

Views: 131

Answers (0)

Related Questions