为什么这个协程会阻塞主线程?

这个函数在while true循环中运行时是有效的。但如果把它放在循环的内部,它将无限等待。

编辑:我已经弄清楚了,等待函数确实有效;但出于某种原因,即使它被包装在一个协程中,它仍然会阻塞主线程。不知道为什么?

function wait(seconds)
    local start = os.time()
    repeat until os.time() > start + seconds
  end

local function countDown()
    while true do
        wait(1)
        if isInNumberGame == true then
            timeSinceLastMessage = timeSinceLastMessage - 1

            if timeSinceLastMessage == 0 then
                isInNumberGame = false
                local messageChannel = mem.guild:getChannel("668605956426563626")

                messageChannel:send("<@"..currentmember.user.id.."> 游戏结束!回答时间到(数字是 "..num..")")
            end
        end
    end
end

local countDownNumGame = coroutine.wrap(countDown)

countDownNumGame()
点赞
用户7652095
用户7652095

由于你使用的是 Discordia,它是使用 luvlibuv 的 Lua 实现)编写的,所以你可以使用在 luv 中存在的 timer 实例。

这是一个可以工作的延迟函数(作者 creationix)

local function delay(ms)
  local thread = coroutine.running()
  local timer = uv.new_timer()
  timer:start(ms, 0, function ()
    timer:close()
    coroutine.resume(thread)
  end)
  coroutine.yield()
end
2020-05-15 03:56:39