gpt4 book ai didi

multithreading - 为什么这个简单的Lua协程不起作用?

转载 作者:行者123 更新时间:2023-12-03 12:53:10 24 4
gpt4 key购买 nike

我有一个非常简单的Lua小代码,是我在自学协程如何工作时编写的。

直到我接受coroutine.wrap之前,我还不错,spec指出:

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. Returns the same values returned by resume, except the first boolean. In case of error, propagates the error.



但是这段代码:
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

最佳答案

这不是coroutine.wrap的工作方式。您必须在第一次调用coroutine.yield时传递enumerator

关于multithreading - 为什么这个简单的Lua协程不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3169946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com