【问题标题】:LÖVE crashes, when using a function in ipairs()在 ipairs() 中使用函数时,LÖVE 崩溃
【发布时间】:2015-04-22 16:56:43
【问题描述】:

我正在对是否能够在 LÖVE 中使用自动生成种子进行实验,但我遇到了问题。当我尝试使用ipairs 将图块添加到游戏中时,它崩溃了。 任何人都可以看到这段代码的问题吗?:

    world = {}

function world.generate()
        for i = 1, 100 do
                world.addTile(i, love.math.random(1, 3), 1)
        end
        local tempWorld = world
        for i,v in ipairs(tempWorld) do
                world.addTile(v.x, v.y+1, 1)
        end
end

function world.addTile(x, y, id)
        for i,v in ipairs(tile) do
                if v.id == id then
                        table.insert(world, {id = id, x = x*tile.w, y = y*tile.h})
                else
                        print("The following id was not recognised: "..id)
                end
        end
end

function world.draw()
        for i,v in ipairs(world) do
                love.graphics.draw(tile.getImage(v.id), v.x, v.y)
        end
end

【问题讨论】:

    标签: function lua lua-table


    【解决方案1】:

    你有一个无限循环。

    local tempWorld = world 不会复制world,它只是创建另一个对它的引用。因此,当world 有另一个由world.addTile 添加的项目时,for 循环:

    for i,v in ipairs(tempWorld) do
       world.addTile(v.x, v.y+1, 1)
    end
    

    有一个新的停止点,因为ipairs 还有一个要迭代的项目。如此重复,直到内存不足。您可能希望保存旧列表的大小:

    local oldsize = #world
    for i=1, oldsize do
       local v = world[i]
       world.addTile(v.x, v.y+1, 1)
    end
    

    现在它的迭代次数不会超过oldsize 次。

    【讨论】:

    • 啊,我不知道!谢谢!这真的很清楚:) 编程愉快!
    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    相关资源
    最近更新 更多