开发者

Why doesn't this simple Lua coroutine work?

I have a very simple little piece of Lua code, which I wrote while teaching myself how coroutines work.

I was fine until I got to coroutine.wrap, the spec states:

coroutine.wrap (f)

Creates a new coroutine, with body f. f must be a Lua function. Returns a function that resumes the coroutine each time it is called. Any arguments passed to the function behave as the extra arguments to resume. Re开发者_C百科turns the same values returned by resume, except the first boolean. In case of error, propagates the error.

However this code:

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)

Complains that yield is nil (on the line I have marked above). As I understand it, yield should be the second argument passed into coroutine.wrap, so where am I going wrong?

Really obvious solution, thanks to the answer below

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


This is not how coroutine.wrap works. You have to pass coroutine.yield in the first call to enumerator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜