# Deleting a item from an array in LUA

This topic is 5409 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello, I´m having problems deleting an item from a Lua array (table). I have some bullets moving on the screen but as soon as I do Bullets=nil to delete one from teh array everything stops. I think it is because this nil assignment but the manual points to do that. Any one can help? Here is the code:
function LinearWeapon(self)
for i,v in ipairs(self.Bullets) do
CnMoveObject(v,0.01,0,0);
Distance=CnGetDistance(v,Players[1].ActorID);
if Distance > 4 then
self.Bullets=nil;
self.NumBullets=self.NumBullets-1;
end
if self.Delay>0 then
self.Delay=self.Delay-1;
end;
end
end



##### Share on other sites
ipairs loops from the 1 entry upwards, until it finds a nil entry. Setting the current entry to nil breaks the loop. Using table.remove on a table you're looping through is probably a bad idea as well, and in fact modifying a table you're looping through may have strange results.

There are several thing you could do.

1) Don't use ipairs for the loop.
for i=1,table.getn (self.Bullets) do local v = self.Bullets -- the rest of your code --end

The problem with this is at the end you still have an array with holes in it. ipairs won't loop through all your values (but pairs will), table.getn won't return the correct highest index in the table.

It is not very difficult to turn a table with holes into a packed one. In fact, you could do it inside the loop:

local k = 1for i=1,table.getn (self.Bullets) do local v = self.Bullets -- the rest of your code --if DontDeleteBulletsI then    if i ~= k then        self.Bullets[k] = self.Bullets    end    k = k + 1else    self.Bullets = nilendend

2) Don't delete the entry, but give it a value that stands for "deleted" (self.Bullets = false could work), and clear all those entries afterwards.

##### Share on other sites
If you store objects in an array and the order doesn't matter, you can always "delete" items by overwriting it with the last item and shrinking the array by 1.
This solution does not solve the "array with holes"-problem in every way, but should work well for your bullet problem.

• 21
• 15
• 9
• 17
• 13