for 循环是否遍历 Lua 和 Love2d 中的空 table?

Does a for loop iterate over an empty table in Lua and Love2d?

我不太确定代码现在发生了什么。全部写在 VScode 中的 Lua 所以我一直只使用 Alt+L 来 运行 它与 love 扩展,因为我实际上没有 Lua编译器设置。当我 运行 代码时,我的想法是点击屏幕,子弹会朝那个方向移动,然后在 0.5 秒后它会消失。

然而,发生的事情是,在我生成一颗子弹后,它会存在一段时间(我认为是 0.5 秒,但我不太确定)然后自行消失。这就是我想要的,但是即使子弹从 table 中移除,我为找到子弹应该行进的方向并将其应用于它的 x 和 y 值所做的计算仍然会继续发生。我不确定这个术语,而且我只使用 LOVE 一两天,所以我不太清楚发生了什么。

代码如下:

function love.load()
    window = {}
    window.x, window.y = love.graphics.getDimensions()

    player = {}
    player.speed = 5
    player.x = window.x/2
    player.y = window.y/2
    player.r = 15
    player.w = {15, 0.5} --speed, duration

    bullets = {} --x, y, direction, speed, duration
    direction = 0
end

function love.update(dt)
    for i=1, #bullets do
        bullets[i][1] = bullets[i][1] + bullets[i][4]*math.cos(bullets[i][3])
        bullets[i][2] = bullets[i][2] + bullets[i][4]*math.sin(bullets[i][3])
        bullets[i][5] = bullets[i][5] - dt
        if bullets[i][5] <= 0 then
            table.remove(bullets, i)
        end
    end
end

function love.draw()
    love.graphics.circle('fill', player.x, player.y, player.r)
    love.graphics.print(direction)
    love.graphics.print('('..love.mouse.getX()..','..love.mouse.getY()..')',0,50)
    love.graphics.print('('..player.x..','..player.y..')',0,100)
    for i=1, #bullets do
        love.graphics.circle('fill', bullets[i][1], bullets[i][2], 5)
    end
end

function love.mousepressed(x, y, button, istouch, presses)
    if button == 1 then
        direction = math.atan((y-player.y)/(x-player.x))
        if player.x > x then direction = direction + math.pi end
        direction = direction + math.random(-10, 10) * math.pi/180
        table.insert(bullets, {player.x, player.y, direction, player.w[1],player.w[2]})
    end
end

当我运行它并按照我之前所说的去做时,这是我收到的错误:

Error

main.lua:18: attempt to index a nil value


Traceback

main.lua:18: in function 'update'
[C]: in function 'xpcall'

第 18 行是这样的:bullets[i][1] = bullets[i][1] + bullets[i][4]*math.cos(bullets[i][3])

我从未在 Lua 中真正开发过,这是我第一次进入游戏开发领域,所以我只是在试验,因此可能编写的代码非常糟糕。感谢您的帮助,谢谢!

在数字 for 循环中,控制表达式仅在循环的第一次迭代之前计算一次。通过在循环中调用 table.remove,您将在 #bullets 已经求值后缩短 bullets,因此它会尝试读取不再存在的元素。 (并且您还为每个删除的元素跳过了一个元素。)在这种情况下,为了快速解决这两个问题,您可以使用 for i=#bullets, 1, -1 do 作为循环。