gpt4 book ai didi

lua协程作为迭代器: cannot resume dead coroutine

转载 作者:行者123 更新时间:2023-12-04 21:40:25 55 4
gpt4 key购买 nike

在那里,

我修改了 Lua 5.0 在线文档中的“perm”示例:http://www.lua.org/pil/9.3.html .我所做的是将 __call() 元方法重新指向 perm() 函数。但它只工作一次,并报告“无法恢复死协程”。知道为什么它不起作用吗?

function permgen (a, n)
if n == 0 then
coroutine.yield(a)
else
for i=1,n do

-- put i-th element as the last one
a[n], a[i] = a[i], a[n]

-- generate all permutations of the other elements
permgen(a, n - 1)

-- restore i-th element
a[n], a[i] = a[i], a[n]

end
end
end

function perm (a)
local n = table.getn(a)
return coroutine.wrap(function () permgen(a, n) end)
end

K = {"a","b","c"}


for p in perm(K) do
print(p[1],p[2],p[3])
end


for p in perm(K) do
print(p[1],p[2],p[3])
end

-- everything above is copied from the Lua online document,
-- my modification is the following
setmetatable(K,{__call=perm(K)})
for p in K do
print(p[1],p[2],p[3])
end

-- cannot repeat!
-- perm.lua:44: cannot resume dead coroutine
for p in K do
print(p[1],p[2],p[3])
end

`

最佳答案

发生这种情况是因为您调用了一次 perm(K) 并将结果分配给 __call 元方法。然后,您使用一次(通过执行 in K),这就完成了由 perm 调用返回的协程的执行。当你第二次尝试这样做时,协程已经“死了”,这会触发错误。

你需要做的是检测协程是否已经死亡并重新创建它。由于您无法使用 coroutine.wrap 执行此操作,因此您需要使用使用 coroutine.create 的解决方案的略微修改版本。这样的事情可能会起作用:

function perm (a)
local n = table.getn(a)
local co = coroutine.create(function () permgen(a, n) end)
return function () -- iterator
if coroutine.status(co) == 'dead' then co = coroutine.create(function () permgen(a, n) end) end
local code, res = coroutine.resume(co)
if not code then return nil end
return res
end
end

它会在恢复之前检查协程的状态,如果它已经死了,那么它会使用相同的参数从头开始重新创建它。

关于lua协程作为迭代器: cannot resume dead coroutine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34325876/

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