2010-07-03 129 views
2

我有一段非常简单的Lua代码,我在教自己如何编写协程时写道。这个简单的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) 

抱怨收率是nil(在I上面已标记的线)。据我了解,yield应该是传入coroutine.wrap的第二个参数,那么我哪里会出错?

真的很明显的解决方案,这要归功于以下

Enumeration.Create = function(generator) 
    local iter = coroutine.wrap(generator, coroutine.yield) 
    return function() 
     return iter(coroutine.yield) 
    end 
end 

回答

4

这答案并不怎么coroutine.wrap作品。您必须在第一次致电enumerator时通过coroutine.yield

+0

Bah,一旦你说它变得如此明显,我只是误解了文档。 – Martin 2010-07-03 01:32:23

+0

为了获得更一致的行为,您需要包装函数的合作,但是如果它们一旦开始生成,Create就可以包装并调用一次来设置yield。 – lhf 2010-07-03 02:00:18

相关问题