Corrutinas en Lua
Pausa en yield, retoma donde quedó.
-- A coroutine pauses at yield and resumes where it left off.
local patrol = coroutine.create(function()
for _, post in ipairs({ "gate", "hall", "crypt" }) do
coroutine.yield("guard reaches the " .. post)
end
return "patrol complete"
end)
print(select(2, coroutine.resume(patrol)))
print(select(2, coroutine.resume(patrol)))
print("Status mid-walk: " .. coroutine.status(patrol))
print(select(2, coroutine.resume(patrol)))
print(select(2, coroutine.resume(patrol)))
print("Status after: " .. coroutine.status(patrol))
Cómo funciona
coroutine.createenvuelve una función en un hilo retomable.yieldmanda un valor afuera y suspende a mitad de bucle.statuslee suspended o dead según avanza la caminata.
Palabras clave y builtins usados aquí
doendforfunctioninipairslocalprintreturnselect
El intento, en números
- Líneas
- 14
- Caracteres a escribir
- 518
- Tokens
- 104
- Ritmo de tres estrellas
- 60 tpm
Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 104 segundos.
Paso 3 de 3 en Patrones y errores; paso 22 de 27 en Fundamentos del lenguaje.