Lua

Lesson 05

Coroutine lifecycle

Check coroutine status and resume results so yielded work cannot fail silently.

Good Code

src/review_worker.lua
local function resume_worker(worker)
  if coroutine.status(worker) == "dead" then
    return nil, "worker already finished"
  end

  -- resume returns success separately from yielded values.
  local ok, result = coroutine.resume(worker)
  if not ok then
    return nil, result
  end

  return result
end

Bad Code

review_worker.lua
local function resume_worker(worker)
  -- The error value is treated like normal work output.
  local _, result = coroutine.resume(worker)
  return result
end

Review Notes

What to review

Good Code

The good version checks whether the coroutine is already dead and keeps the ok flag from resume. Errors return as error values, not normal task output.

Bad Code

The bad version ignores the success flag. A runtime error inside the coroutine can look like a normal yielded result.

Takeaways

  • Lua coroutine code should inspect resume success and status before assuming a task advanced.