我如何处理没有coroutine.yield()的Lua库?

Ank*_*nko 5 lua modularity luasocket coroutine

我想下载一个大文件并同时处理其他事情.

但是,luasocket.http从不打电话coroutine.yield().文件下载时,其他所有内容都会冻结.

这是一个说明性示例,我尝试同时下载文件并打印一些数字:

local http = require'socket.http'

local downloadRoutine = coroutine.create(function ()
    print 'Downloading large file'
    -- Download an example file
    local url = 'http://ipv4.download.thinkbroadband.com/5MB.zip'
    local result, status = http.request(url)
    print('FINISHED download ('..status..', '..#result..'bytes)')
end)

local printRoutine = coroutine.create(function ()
    -- Print some numbers
    for i=1,10 do
        print(i)
        coroutine.yield()
    end
    print 'FINISHED printing numbers'
end)

repeat
    local printActive = coroutine.resume(printRoutine)
    local downloadActive = coroutine.resume(downloadRoutine)
until not downloadActive and not printActive
print 'Both done!'
Run Code Online (Sandbox Code Playgroud)

运行它会产生这样的:

1
Downloading large file
FINISHED download (200, 5242880bytes)
2
3
4
5
6
7
8
9
10
FINISHED printing numbers
Both done!
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,printRoutineresume第一天.它打印数字1和yields.然后downloadRoutineresumed,它会下载整个文件而不会屈服.只有这样才能打印其余的数字.

我不想写自己的套接字库!我能做什么?

编辑(当天晚些时候):一些MUSH用户也注意到了.他们提供有用的想法.

Pau*_*nko 5

我不明白为什么你不能使用PiL建议copas库(这几乎与这里给出的答案相同).

Copas包装套接字接口(不是socket.http),但你可以使用低级接口来获得你需要的东西(不测试):

require("socket")
local conn = socket.tcp()
conn:connect("ipv4.download.thinkbroadband.com", 80)
conn:send("GET /5MB.zip HTTP/1.1\n\n")
local file, err = conn:receive()
print(err or file)
conn:close()
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用addthreadcopas为您提供非阻塞套接字,step/loopreceive在有东西可以接收时使用函数.

使用copas的工作量较少,而settimeout(0)直接使用则可以让您获得更多控制权.