Lua 协同程序(coroutine)是一种轻量级的并发机制,它允许你在函数中挂起和恢复执行。这种机制特别适合于编写迭代器和实现简单的并发。下面我将详细解释如何使用 Lua 协同程序,并给出一个小项目的完整代码。
基本语法和概念
创建协同程序:
使用coroutine.create()
创建一个新的协同程序对象,它接受一个函数作为参数。local co = coroutine.create(function() print("Coroutine started") coroutine.yield("yielded a value") print("Coroutine resumed") end)
启动和恢复协同程序:
使用coroutine.resume()
启动或恢复一个协同程序的执行。当协同程序挂起时,coroutine.resume()
会恢复它的执行。local status, result = coroutine.resume(co) print(result) -- 输出 "yielded a value"
挂起协同程序:
使用coroutine.yield()
挂起当前协同程序的执行,并返回一个值给coroutine.resume()
的调用者。-- 继续从上次挂起的地方执行 local status, result = coroutine.resume(co) print(result) -- 输出 "Coroutine resumed"
小项目完整代码
以下是一个简单的 Lua 脚本,演示了如何使用协同程序来实现一个简单的任务队列处理器。
```lua
-- 文件名:coroutine_example.lua
-- 创建一个协同程序,模拟任务队列处理器
local function taskProcessor()
while true do
local task = coroutine.yield() -- 等待接收任务
print("Processing task: " .. task)
end
end
-- 创建协同程序对象
local processor = coroutine.create(taskProcessor)
-- 启动协同程序,直到第一次挂起
assert(coroutine.resume(processor))
-- 向协同程序发送任务并处理
local tasks = {"Task 1", "Task 2", "Task 3"}
for _, task in ipairs(tasks) do
local status, result = coroutine.resume(processor, task)
if not status then
print("Error: " .. result)
break
end
end