如何在lua中创建Python生成器?
我正试图将这个Python代码转换成lua,但我真的无法理解它。问题是,在python中,for循环在函数产生后自动恢复函数,但我不确定如何在lua中做到这一点。任何帮助都将不胜感激 以下是定义函数的代码:如何在lua中创建Python生成器?,python,lua,generator,coroutine,Python,Lua,Generator,Coroutine,我正试图将这个Python代码转换成lua,但我真的无法理解它。问题是,在python中,for循环在函数产生后自动恢复函数,但我不确定如何在lua中做到这一点。任何帮助都将不胜感激 以下是定义函数的代码: def良好路径(self、x、y、dx、dy、budget、seen=None): 如果没有看到: seen=set() 如果预算>=0: 收益率(),(x,y,dx,dy) 如果预算=0,则 协程产量({},x,y,dx,dy) 结束 如果有预算,请浏览和,看看这个网站是如何运作的,并帮助
def良好路径(self、x、y、dx、dy、budget、seen=None):
如果没有看到:
seen=set()
如果预算>=0:
收益率(),(x,y,dx,dy)
如果预算=0,则
协程产量({},x,y,dx,dy)
结束
如果有预算,请浏览和,看看这个网站是如何运作的,并帮助您改进当前和未来的问题,这可以帮助您获得更好的答案。“演示如何解决此编码问题?”与堆栈溢出无关。您必须诚实地尝试解决方案,然后询问有关实现的具体问题。堆栈溢出不是为了取代现有的教程和文档。我已经编辑了这篇文章,希望现在可以了。更好,是的。如果您提供预期的see,您将有更好的机会获得良好的响应。我不会是那个人,因为我已经五年没有接触Lua了。我不知道Lua
是否可以创建生成器,但在许多情况下,您可以创建转换代码到普通函数,该函数在开始时创建空列表,它将结果附加到该列表,而不是产生-最后它返回完整列表。您应该使用4个变量,而不是到此结束
。代码的其余部分看起来正常。你现在有什么问题?
function mitm:good_paths(x, y, dx, dy, budget, seen)
local co
co = coroutine.create(function(x, y, dx, dy, budget, seen)
if seen == nil then
seen = {}
end
if budget >= 0 then
coroutine.yield({}, x, y, dx, dy)
end
if budget <= 0 then
return
end
if not Misc.checkInList(seen, x .. ", " .. y) then
table.insert(seen, x .. ", " .. y)
end
local x1, y1 = x + dx, y + dy
if not Misc.checkInList(seen, x1 .. ", " .. y1) then
for path, thisEnd in self:good_paths(x1, y1, -dy, dx, budget - self.lr_price, seen) do
coroutine.yield(table.insert(path, L, 1), thisEnd)
end
for path, thisEnd in self:good_paths(x1, y1, dy, -dx, budget - self.lr_price, seen) do
coroutine.yield(table.insert(path, R, 1), thisEnd)
end
table.insert(seen, x1 .. ", " .. y1)
local x2, y2 = x1 + dx, y1 + dy
if not Misc.checkInList(seen, x2 .. ", " .. y2) then
for path, thisEnd in self:good_paths(x2, y2, dx, dy, budget - self.t_price, seen) do
coroutine.yield(table.insert(path, T, 1), thisEnd)
end
end
local removeIndex
for index, val in pairs(seen) do
if val == x1 .. ", " .. y1 then
removeIndex = index
break
end
end
table.remove(seen, removeIndex)
end
local removeIndex
for index, val in pairs(seen) do
if val == x .. ", " .. y then
removeIndex = index
break
end
end
table.remove(seen, removeIndex)
end)
local iterator = function ()
local code, path1, x1, y1, dx1, dy1 = coroutine.resume(co, x, y, dx, dy, budget, seen)
return path1, x1, y1, dx1, dy1
end
return iterator
end
function mitm:prepare(budget)
local dx0, dy0 = 0, 1
for path, x, y, dx, dy in self:good_paths(0, 0, dx0, dy0, budget) do
print(path, x, y, dx, dy)
table.insert(self.list, {path, x, y, dx, dy})
if not self.inv[x .. ", " .. y .. ", " .. dx .. ", " .. dy] then
self.inv[x .. ", " .. y .. ", " .. dx .. ", " .. dy] = {}
end
table.insert(self.inv[x .. ", " .. y .. ", " .. dx .. ", " .. dy], path)
end
end