Lua 和 Love2d 中的 for 循环如何迭代空表?

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

但是,当我生成子弹后,它会存在一段时间(我认为是0.5秒,但我不太确定),然后自动消失。 这就是我想要的,但是尽管子弹已经从表格中移除,我计算出的应该移动并应用到 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

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

错误

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,这是我第一次涉足游戏开发,所以我只是在尝试,因此代码可能非常糟糕。感谢任何帮助,谢谢!

原文链接 https://stackoverflow.com/questions/69982533

点赞
stackoverflow用户7509065
stackoverflow用户7509065

在数值型的 for 循环中,控制表达式只会在第一次迭代之前被评估一次。当你在循环中调用 table.remove 时,你正在缩短 bullets,而此时 #bullets 已经被评估过了,所以它会尝试读取不再存在的元素。(而且每次删除一个元素时,你也会跳过一个元素。)对于这种情况的两个问题的快速解决方案,你可以在循环中使用 for i=#bullets, 1, -1 do

2021-11-16 02:59:54