【发布时间】:2011-03-11 08:12:12
【问题描述】:
我有一段非常简单的 Lua 代码,是我在自学协程如何工作时编写的。
直到我进入 coroutine.wrap 之前我都很好,spec 状态:
coroutine.wrap (f)
创建一个新的协程,主体为 f。 f 必须是 Lua 函数。返回一个 恢复协程的函数 每次调用它。任何论据 传递给函数的行为就像 恢复的额外参数。返回 resume 返回的值相同,除了 第一个布尔值。万一出错, 传播错误。
但是这段代码:
Enumeration = {}
Enumeration.Create = function(generator)
return coroutine.wrap(generator, coroutine.yield)
end
local function TestEnumerator(yield)
yield(1) --ERROR HERE
yield(2)
yield(3)
end
local enumerator = Enumeration.Create(TestEnumerator)
local first = enumerator()
local second = enumerator()
local third = enumerator()
print (first, second, third)
抱怨产量为零(在我上面标记的行上)。据我了解,yield 应该是传递给 coroutine.wrap 的第二个参数,那么我哪里错了?
非常明显的解决方案,感谢下面的答案
Enumeration.Create = function(generator)
local iter = coroutine.wrap(generator, coroutine.yield)
return function()
return iter(coroutine.yield)
end
end
【问题讨论】:
标签: multithreading lua coroutine