约 2378 字

约 12 分钟

#协程

协程可以暂停函数的执行并保留它的局部状态。调用方恢复协程时,函数从上次暂停的位置继续。一个常见用途是按需生成数据,让循环每次只取一个结果。

#启动、暂停与恢复

coroutine.create(f) 返回一个协程对象,初始状态为 suspended。第一次 resume 将参数传给入口函数。此后,协程和调用方可以通过 yield 与 resume 交换数据。

local worker = coroutine.create(function(first)
    local next_value = coroutine.yield(first * 2)
    return next_value + 1
end)

print(coroutine.status(worker)) -- suspended

local ok, value = coroutine.resume(worker, 5)
print(ok, value, coroutine.status(worker)) -- true  10  suspended

ok, value = coroutine.resume(worker, 20)
print(ok, value, coroutine.status(worker)) -- true  21  dead

第一次恢复把 5 交给入口函数。yield(10) 暂停协程,外层的 resume 收到 true, 10,此时给 next_value 的赋值还在等待。第二次恢复让 yield 返回 20,随后协程从赋值处继续,最终返回 21。

状态何时出现
suspended刚创建,或执行到 yield 后等待恢复
running正在执行,协程可从内部观察到自己的这个状态
normal协程已经启动,此刻正在等待它恢复的另一个协程让出或返回
dead入口函数已返回,或执行因错误结束

执行权在调用 resume 和 yield 时交接。若协程执行一段长计算而期间始终没有让出,调用方会一直等到它返回。

#用协程实现迭代器

下面的 range 返回一个迭代器。第一次调用迭代器时,coroutine.wrap 启动内部协程。每次遇到 coroutine.yield,协程把一个值交给外层循环,并暂停执行。

local function range(first, last, step)
    return coroutine.wrap(function()
        for value = first, last, step do
            coroutine.yield(value)
        end
    end)
end

for value in range(2, 8, 2) do
    print(value)
end
2
4
6
8

内层循环结束时,协程函数返回,迭代器就没有下一个值,外层循环随之结束。泛型 for 将迭代器返回的第一个 nil 当作结束信号,所以示例只通过 yield 交出有效数值。这个迭代器只保存进行到哪一步,可以用于逐个处理大量结果。

#处理错误和提前结束

coroutine.resume 用第一个返回值表示是否成功。成功时,其余返回值来自 yield 或入口函数的 return。失败时,第二个返回值是错误对象。coroutine.wrap 提供的函数会省略这个布尔值,并在遇到错误时关闭协程、向调用者抛出错误。

若调用方可以提前停止,且协程持有文件等资源,使用 create 可以保留协程对象。Lua 5.4 的 coroutine.close 可以关闭暂停或死亡的协程,释放内部尚待关闭的资源。

local handle
local worker = coroutine.create(function()
    local file <close> = assert(io.tmpfile())
    handle = file
    coroutine.yield()
end)

assert(coroutine.resume(worker))
print(coroutine.status(worker), io.type(handle)) -- suspended  file

assert(coroutine.close(worker))
print(coroutine.status(worker), io.type(handle)) -- dead  closed file

协程暂停时,局部变量仍处于作用域内,文件保持打开。关闭协程后,文件随 <close> 变量一起关闭。使用 resume 时,若协程因错误停止,调用方也可用 close 清理待关闭变量。此时 close 可以返回 false 和原来的错误对象,因此在错误处理路径中应检查这个返回值。

更新: 2026/11/28

作者: planc

创建: 2026/11/28