API coroutine.resume

From Warcraft Wiki
Jump to navigation Jump to search

Begins or resumes a coroutine.

success [, ...] = coroutine.resume(co [, ...])
success, errMsg = coroutine.resume(co [, ...])

Arguments

co
thread - A suspended coroutine.
...
Variable arguments - Return values for coroutine.yield() when resuming, or the function header if it didn't begin yet.

Returns

success
boolean - true when the coroutine runs without error.
...
Variable arguments - Arguments supplied to coroutine.yield() if the coroutine yielded, or return values if it reached the end.
errMsg
string - A description of the error, or why success was false.

Details

  • There is an implicit pcall(), so execution can resume even when an error occurs inside the coroutine.
  • If the coroutine had previously reached its conclusion, success will be false.

Example

Yields every 1ms and resumes on the next frame until completion.

local function workload(stopTime)
	for i=1, 1000000 do
		-- wasting time
		local x = i * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9
		if GetTimePreciseSec() >= stopTime then
			stopTime = coroutine.yield(1000000 - i)  -- passes the number of iterations left, receives a new stopTime
		end
	end
end

local co = coroutine.create(workload)

local ticker
ticker = C_Timer.NewTicker(0, function()
	local success, remaining = coroutine.resume(co, GetTimePreciseSec() + 0.001)
    if success and remaining then
		print("There are " .. remaining .. " iterations left.")
	else
		ticker:Cancel()
		print("Reached the end!")
	end
end)

External links