举例详解Lua中的协同程序编程
协同程序允许函数以可控方式交替执行,同一时刻仅一个协程运行,通过resume启动、yield主动暂停并传参。示例展示协程创建、参数传递及返回值机制,循环生成数字时协程耗尽可自动重建。协程非并发,但能精确控制执行顺序并保存中间状态。
首先要搞清楚一个基本概念:协程(协同程序)本质上是一种程序控制机制,它允许两个或更多的函数方法以可控制的方式交替执行。关键点在于,在任何给定的时刻,只有一个协程在运行——正在运行的协程只有在主动要求暂停时,才会把执行权交出去。
这个定义乍看有点绕?换个更直观的说法:假设我们有主程序和协程两个角色。当我们调用 resume 来启动协程,它就开始执行;当它执行到 yield 时,就主动暂停,把控制权还给调用方。下次再调用 resume,协程会从刚才暂停的地方接着往下跑。这个过程可以一直持续,直到协程执行完毕。
协程可用的功能
下表列出了 Lua 中协程相关的全部函数及其用途:

举个具体的例子
直接上代码,通过运行结果来理解协程的工作流程:
co = coroutine.create(function (value1,value2)
local tempvar3 =10
print("coroutine section 1", value1, value2, tempvar3)
local tempvar1 = coroutine.yield(value1+1,value2+1)
tempvar3 = tempvar3 + value1
print("coroutine section 2",tempvar1 ,tempvar2, tempvar3)
local tempvar1, tempvar2= coroutine.yield(value1+value2, value1-value2)
tempvar3 = tempvar3 + value1
print("coroutine section 3",tempvar1,tempvar2, tempvar3)
return value2, "end"
end)
print("main", coroutine.resume(co, 3, 2))
print("main", coroutine.resume(co, 12,14))
print("main", coroutine.resume(co, 5, 6))
print("main", coroutine.resume(co, 10, 20))
运行输出:
coroutine section 1 3 2 10
main true 4 3
coroutine section 2 12 nil 13
main true 5 1
coroutine section 3 5 6 16
main true 2 end
main false cannot resume dead coroutine
这段代码到底在做什么?
从头捋一遍:我们用 resume 启动协程,用 yield 让它暂停。注意,每次 resume 调用都能收到多个返回值,这正是协程灵活性的体现。
- 首先创建一个协程,并赋值给变量
co,它需要两个参数。 - 第一次调用
resume(co, 3, 2)时,传入的值 3 和 2 分别赋给value1和value2,这个赋值会一直保持到协程结束。 - 为了更清楚地看到变量的变化,我们初始化了
tempvar3 = 10。后续执行中,由于value1始终为 3,tempvar3会依次变成 13 和 16。 - 第一个
yield返回了两个值:4 和 3(由value1+1, value2+1得出)。同时,resume还会收到一个布尔值表示协程是否正常执行。 - 看到没有?
yield的返回值来自于下一次resume传入的参数。比如第二次resume(co, 12,14)中的 12 和 14,会被yield赋给变量tempvar1(和tempvar2,但这里tempvar2未定义所以输出 nil)。这种机制让协程能够在挂起状态下“记住”之前的数据,同时还能接收新的输入,非常强大。 - 最后,当协程内所有语句都执行完毕后,再次调用
resume会返回false和错误信息 "cannot resume dead coroutine"。
另一个典型用例:循环生成数字
下面这个协程每次调用返回一个 1 到 5 之间的数字,用完了就重新创建协程继续:
function getNumber()
local function getNumberHelper()
co = coroutine.create(function ()
coroutine.yield(1)
coroutine.yield(2)
coroutine.yield(3)
coroutine.yield(4)
coroutine.yield(5)
end)
return co
end
if(numberHelper) then
status, number = coroutine.resume(numberHelper);
if coroutine.status(numberHelper) == "dead" then
numberHelper = getNumberHelper()
status, number = coroutine.resume(numberHelper);
end
return number
else
numberHelper = getNumberHelper()
status, number = coroutine.resume(numberHelper);
return number
end
end
for index = 1, 10 do
print(index, getNumber())
end
输出结果:
1 1
2 2
3 3
4 4
5 5
6 1
7 2
8 3
9 4
10 5
可以看到,每 5 次调用后,协程“耗尽”,然后自动重建,继续循环输出 1~5。
很多人会把协程和多线程编程中的线程做比较,但必须明确:协程虽然拥有类似线程的“暂停-恢复”能力,但同一时间只有一个在执行,它并不会并发运行。协程的核心价值在于让我们精确控制程序的执行顺序,同时保存必要的中间状态。如果再配合全局变量,协程的灵活性还能进一步提升——这也是 Lua 中实现协作式任务调度的基础。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















