I just started using Love about a week ago and have made okay progress on my Galaga clone. Overall things are going smoothly, but I can't figure out why the value of #WeaponManager does not decrease.
function WeaponManager:move(dt)
for i,v in ipairs(WeaponManager) do
if WeaponManager[i] ~= nil then
-- Removes a Weapon from the table if off screen
if (v.x + v.image:getHeight() < 0 or v.x > love.graphics.getWidth() or
v.y + v.image:getWidth() < 0 or v.y > love.graphics.getHeight()) then
table.remove(v)
else
v:move(dt)
end
end
end
end
I am open to any feedback especially recommendations to improve the code. This my first time making a game and using Love. I've read PIL, but haven't spend a lot of time with Lua. Also, I come from a mostly Java background.
Another nice benefit of table.remove() over setting the index to nil is that table.remove() will automatically re-order your indexes to fill the gap left by the removed index. If you have {1, 2, 3, 4, etc.} and use table.remove() on index 3, index 4 will get bumped to 3 and so on until the list is whole and in order again.
Having a table with gaps in the indexes can do weird things when using iterators like ipairs() or even sometimes when using a numerical for loop.
Ensayia wrote:Another nice benefit of table.remove() over setting the index to nil is that table.remove() will automatically re-order your indexes to fill the gap left by the removed index. If you have {1, 2, 3, 4, etc.} and use table.remove() on index 3, index 4 will get bumped to 3 and so on until the list is whole and in order again.
Having a table with gaps in the indexes can do weird things when using iterators like ipairs() or even sometimes when using a numerical for loop.
Related: If you remove an item with table.remove() while you are iterating that table you will run into problems related to the reindexing behavior. You need to either make a list of objects to remove, and remove them after you finish iterating. Or, you need to iterate backwards so that any index reshuffling happens to items you've already iterated over.
That's because a lua 'array' has no gaps in it. In fact, in the lua core there are two parts to a table, an array and a hashmap, with small gaps it will stay in the array, if there's a bigger gap (don't know the exact numbers, but t[1] and t[3000] should do it), the non-array part (the one at index 3000) will be in the hashmap, not the array.