【发布时间】:2015-12-17 02:56:16
【问题描述】:
那里,
我修改了 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
`
【问题讨论】:
-
您将
__call设置为调用perm(K)的结果。您的意思是让__call实际上调用perm函数吗?