2

下面的update()函数在游戏的每一帧上都会被调用。如果Drop粒子的 y 值大于 160,我想将其从表中删除。问题是我收到“尝试将数字与零进行比较”错误,如下所示:

local particles = {};

function update()
    local num = math.random(1,10);
    if(num < 4) then
        local drop = Drop.new()
        table.insert ( particles, drop );
    end

    for i,val in ipairs(particles) do
        if(val.y > 160) then --ERROR attempt to compare number with nil
            val:removeSelf(); --removeSelf() is Corona function that removes the display object from the screen
            val = nil;
        end
    end
end

我究竟做错了什么?显然val是 nil,但我不明白为什么表迭代会首先找到 val,因为当它的 y 值大于 160 时我将它设置为 nil。

4

4 回答 4

3

感谢您的回答,他们都很有帮助。这就是最终为我工作的东西。table.remove调用是保持循环正常运行所必需的。

for i = #particles, 1, -1 do
    if particles[i].y > 160 then
        local child = table.remove(particles, i)
        if child ~= nil then
            display.remove(child)
            child = nil
        end
    end
end
于 2011-06-01T16:59:42.293 回答
2

你找错地方了,问题不是那个valnil而是val.y那个nil。看这个例子:

> x=nil
> if x.y > 10 then print("test") end
stdin:1: attempt to index global 'x' (a nil value)
stack traceback:
    stdin:1: in main chunk
    [C]: ?
> x={y=nil}
> if x.y > 10 then print("test") end
stdin:1: attempt to compare number with nil
stack traceback:
    stdin:1: in main chunk
    [C]: ?

此外,当您设置valnil时,可能不会做任何事情(我相信val是副本):

> t={"a", "b", "c", "d"}
> for i,val in ipairs(t) do print(i, val) end
1   a
2   b
3   c
4   d
> for i,val in ipairs(t) do if i==3 then print("delete", val); val=nil end end
delete  c
> for i,val in ipairs(t) do print(i, val) end
1   a
2   b
3   c
4   d

编辑:要从表中删除元素,您需要table.remove

> t[3]=nil
> for i,val in ipairs(t) do print(i, val) end
1   a
2   b
> t[3]="c"
> for i,val in ipairs(t) do print(i, val) end
1   a
2   b
3   c
4   d
> for i,val in ipairs(t) do if i==3 then print("delete", val); table.remove(t, i) end end
delete  c
> for i,val in ipairs(t) do print(i, val) end
1   a
2   b
3   d
于 2011-06-01T00:13:01.537 回答
0

我认为您不允许在ipairs 迭代表时修改表的内容。我依稀记得读过我的Lua 5.1 参考手册的硬拷贝,但我现在似乎找不到它。当您将val设置为nil时,它会从粒子表中删除一个元素。

您可以尝试反向处理表,因为您的函数正在对粒子表进行全面扫描,有条件地删除一些项目:

for x = #particles, 1, -1 do
    if particles[x].y > 160 then
        particles[x]:removeSelf()
        particles[x] = nil
    end
end
于 2011-05-31T23:25:28.743 回答
0

JeffK 的解决方案应该有效,但我认为它有效的原因不是因为他正在向后遍历列表,而是因为他正在设置particles[i] = nil而不是val = nil. 如果你运行val = nil,你只是将 val 的本地副本设置为 nil,而不是表中的条目。

尝试这个:

for i,val in ipairs(particles) do
    if(val.y > 160) then
        particles[i]:removeSelf()
        particles[i] = nil;
    end
end
于 2011-06-01T00:05:26.960 回答