Coroutine problems

Hi, I want to make a system where you can cancel a function while it’s running. So I call the function in a coroutine, but I also want to check if it errors, so I need to check when it stops running, and be able to determine whether it errored or just finished. But if I use coroutines, that defeats the whole purposes of yielding for it to stop. I just want to include the functionality of coroutine.close, not the asynchronous part.

Here’s my question: Is there any way to check when a coroutine stops, or errors, and yield for it to finish at the same time?

Inside this coroutine, there’s a loop that continues executing tasks until the closeSignal is set to true . The CLOSE section initializes a closeSignal to false , creates a coroutine handle, and starts the coroutine. After simulating work with wait(1) , the closeSignal is set to true , signaling the coroutine to close. It then checks the status and result of the coroutine, printing a message based on whether it completed successfully or encountered an error.

-- Define a coroutine function
function myCoroutine(closeSignal)
    local success, result

    -- Use pcall to catch errors
    success, result = pcall(function()
        while not closeSignal do

            -- Simulate some work
            wait(2)
        end

        -- If everything is fine, set success to true
        success = true
    end)

    -- Return success and result
    return success, result
end

-- CLOSE
local closeSignal = false  -- Signal to indicate when to close the coroutine
local coroutineHandle = coroutine.create(function()
    myCoroutine(closeSignal)
end)

-- Start the coroutine
coroutine.resume(coroutineHandle)

-- Simulate some work
wait(1)

-- Set the closeSignal to true to stop the coroutine
closeSignal = true

-- Check the status and result
local success, result = coroutine.resume(coroutineHandle)

-- Print the result based on success or failure
if success then
    print("Coroutine completed successfully:", result)
else
    print("Coroutine encountered an error:", result)
end

1 Like

I already found a solution to my problem, forgot to mark this, but I’ll mark yours as the solution for now.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.