Lesson 15 of 15

Coroutines Overview

Coroutines

Coroutines are one of Lua's most powerful features. They allow cooperative multitasking by letting functions suspend and resume execution.

function producer()
  local i = 0
  while true do
    i = i + 1
    coroutine.yield(i)
  end
end

A coroutine is created with coroutine.create and resumed with coroutine.resume. Each yield pauses execution and returns a value.

Since coroutines require runtime support beyond our transpiler, in this lesson we will simulate the pattern using closures that mimic coroutine behavior:

function makeRange(start, stop)
  local i = start - 1
  return function()
    i = i + 1
    if i <= stop then
      return i
    end
    return nil
  end
end

Iterator Pattern

This closure-based approach is how many Lua iterators work under the hood.

Your Task

Write a fibonacci function that returns an iterator. Each call to the iterator returns the next Fibonacci number. The sequence starts: 1, 1, 2, 3, 5, 8, ...

JS Transpiler loading...
Loading...
Click "Run" to execute your code.