什么导致Lua中嵌套迭代器调用出错?

我有一个列表类的以下迭代器:

ListIterator = Class:new({
    current = nil;
    __call = function(self)
        self.current = self.current.next
        if self.current ~= nil then return self.current.value else return nil end
    end;
})

可以使用以下方式创建迭代器:

copy = function(self)
    local out = List:new()
    local current = self.list
    while current ~= nil do
        List:add(current.value)
        current = current.next
    end
    return out
end;

each = function(self)
    return ListIterator:new({ current = { next = self:copy().list, value = nil } })
end;

以下示例会导致我陷入无限循环:

l = List:new()
l:add("a")
l:add("b")
l:add("c")
l:add("d")
l:add("e")
for x in l:each() do
    for y in l:each() do
        print(x..y)
    end
end

我已经为每个迭代器创建了列表的副本,并使用了不同的对象。我不知道如何防止这种行为。我认为这可能与使用在Lua教程中的示例中返回的函数上的方法本地变量有关,但使迭代器成为完整的对象并没有解决这个问题。

点赞