Coroutine

Uma coroutine é uma ferramenta de programação que permite pausar e retomar funções em determinados pontos. Diferente das funções regulares que executam completamente, as coroutines param em pausas designadas e continuam depois. Essa funcionalidade é útil para gerenciar tarefas que precisam ocorrer ao longo do tempo sem parar todo o programa.
Descrição
YieldA operação usada dentro de uma coroutine para pausar sua execução, permitindo que outro código seja executado. Ela para temporariamente a coroutine e salva seu estado.
ResumeA operação que reinicia uma coroutine do ponto onde ela foi pausada pela última vez, continuando sua execução.
StatusUma função para verificar o estado atual de uma coroutine, como se está suspensa, executando ou morta (completada).
WrapUma função wrapper que irá retomar uma coroutine específica quando chamada e retornará apenas os valores pausados.

Exemplo: Coroutine

local function countingCoroutine()
	for i = 1, 3 do  -- Count from 1 to 3
		coroutine.yield("Count: " .. i)  -- Yield the count value
	end
	return "Counting completed."  -- Return a final message when done
end

-- Create the coroutine from the function
local co = coroutine.create(countingCoroutine)

-- Start the coroutine and check the status and results at each step
print("Starting coroutine...")
print("Status before start:", coroutine.status(co))  -- Initially, status should be 'suspended'

local success, result = coroutine.resume(co)  -- Resume for the first count
print(success, result)  -- Should print true, "Count: 1"
print("Status after first count:", coroutine.status(co))  -- Should still be 'suspended'

success, result = coroutine.resume(co)  -- Resume for the second count
print(success, result)  -- Should print true, "Count: 2"
print("Status after second count:", coroutine.status(co))  -- Should still be 'suspended'

success, result = coroutine.resume(co)  -- Resume for the third count
print(success, result)  -- Should print true, "Count: 3"
print("Status after third count:", coroutine.status(co))  -- Should still be 'suspended'

success, result = coroutine.resume(co)  -- Resume for the final return
print(success, result)  -- Should print true, "Counting completed."
print("Status after completion:", coroutine.status(co))  -- Should now be 'dead'

-- Check status after completion to confirm no further actions can be taken
success, result = coroutine.resume(co)
print(success, result)  -- Should print false and possibly an error message
print("Status after attempting to resume a completed coroutine:", coroutine.status(co))  -- Should be 'dead'
Image 1
Roblox Studio

Exemplo: Usando coroutine.wrap

local function countToThree()
	for i = 1, 3 do
		coroutine.yield("Count: " .. i)  -- Yield with a return value
	end
	return "Counting completed."  -- Return a final message when done
end

local wrappedCoroutine = coroutine.wrap(countToThree)

print("Starting coroutine...")
local result
result = wrappedCoroutine()  -- Executes and yields "Count: 1"
print(result)  -- Prints "Count: 1"
result = wrappedCoroutine()  -- Resumes and yields "Count: 2"
print(result)  -- Prints "Count: 2"
result = wrappedCoroutine()  -- Resumes and yields "Count: 3"
print(result)  -- Prints "Count: 3"
result = wrappedCoroutine()  -- Ends the counting, returns "Counting completed."
print(result)  -- Prints "Counting completed."
result = wrappedCoroutine()  -- Error
Image 1
Roblox Studio

Se você achou este tutorial útil e gostaria de apoiar meu trabalho, por favor, considere me comprar um café.

Muito obrigado pelo seu apoio!

Me compre um café