Lua协程
协程
什么是协程
协程的特点
协程和线程的区别
协程的工作原理
Lua协程示例
-- 模拟一个简易的异步任务示例
function longRunningTask()
local value = 0
for i = 1, 3 do
value = value + 1
print("Running step", i, "with value", value)
coroutine.yield(value)
end
return value
end
-- 创建协程
local co = coroutine.create(longRunningTask)
--[[
coroutine.resume 返回两个值:
布尔值,表示协程是否成功执行。true 表示协程成功执行,false 表示遇到了错误。
其他返回值,它们依赖于协程内部的执行情况:
如果协程在 coroutine.yield 处暂停,该处的返回值会作为 resume 的第二个返回值。
如果协程正常结束,coroutine.resume 的第二个返回值是协程结束时coroutine.yield(*)传入的返回值。
如果协程遇到运行错误,coroutine.resume 的第二个返回值是错误消息。
--]]
-- 恢复协程,接收每次 yield 返回的值
local status, result = coroutine.resume(co) -- 输出 "Running step 1 with value 1"
local r = coroutine.status(co)
print("Received from yield:", status,result,r)
-- can todo something... 处理其他任务,等待下一次启动协程
status, result = coroutine.resume(co) -- 输出 "Running step 2 with value 2"
r = coroutine.status(co)
print("Received from yield:", status,result,r)
-- can todo something...
status, result = coroutine.resume(co) -- 输出 "Running step 3 with value 3"
r = coroutine.status(co)
print("Received from yield:", status,result,r)
-- can todo something...
status, result = coroutine.resume(co) -- 协程完成,返回最终结果
r = coroutine.status(co)
print("Final result:", status,result,r)