1

This function works until I put it in a while true do loop. It will wait infinitely if I put it inside the loop.

EDIT: I've figured out the wait does work; however, for some reason, even though it's wrapped in a coroutine, it is halting the main thread. Not sure why?

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.."> Game over! Out of time to respond (the number was "..num..")")
            end
        end
    end
end

local countDownNumGame = coroutine.wrap(countDown)

countDownNumGame()

Srentol
  • 13
  • 3
  • Does this answer your question? [How to add a "sleep" or "wait" to my Lua Script?](https://stackoverflow.com/questions/17987618/how-to-add-a-sleep-or-wait-to-my-lua-script) – Ali Deym May 15 '20 at 03:26
  • Can you please provide more information of what libraries or platform you are using? – Ali Deym May 15 '20 at 04:01
  • I am using discordia as my library. Roblox Lua is what I am experienced with, but you said Lua is a single thread language. I would like that while true do loop to not interrupt the rest of the code and just run in the background. I thought that was the use of a coroutine. Is it not? – Srentol May 15 '20 at 04:04
  • If not, what should I use so that it will not pause the thread? – Srentol May 15 '20 at 04:06

1 Answers1

0

Since you are using Discordia, which is using luv (lua implementation of libuv), you can use timer instances that are present in luv.

Here is a working delay function (Author 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
Ali Deym
  • 142
  • 8