Coroutines let you write cooperative multitasking.
Creating Coroutines
LUA
local co = coroutine.create(function()
print("Step 1")
coroutine.yield() -- pause
print("Step 2")
coroutine.yield() -- pause
print("Step 3")
end)
coroutine.resume(co) -- "Step 1"
coroutine.resume(co) -- "Step 2"
coroutine.resume(co) -- "Step 3"Passing Data
LUA
local co = coroutine.create(function()
local name = coroutine.yield("What is your name?")
local age = coroutine.yield("How old are you?")
return "Hello " .. name .. ", age " .. age
end
local _, question = coroutine.resume(co)
print(question) -- "What is your name?"
local _, question2 = coroutine.resume(co, "Sita")
print(question2) -- "How old are you?"
local _, result = coroutine.resume(co, 21)
print(result) -- "Hello Sita, age 21"Error Handling in Lua
LUA
-- pcall protects against errors
local ok, result = pcall(function()
error("Something went wrong")
end)
if ok then
print("Success:", result)
else
print("Error:", result)
endassert and error
LUA
local function divide(a, b)
assert(b ~= 0, "Cannot divide by zero")
return a / b
endTips
- Use
pcallfor safe error handling. - Coroutines are great for game loops, async I/O, and generators.
- Use
assertfor precondition checks.
🎉 You have completed the Lua course!