Jump to content
  • Advertisement
Sign in to follow this  
HexDump

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.

If you intended to correct an error in the post then please contact us.

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

Thanks in advance, HexDump.

Share this post


Link to post
Share on other sites
Advertisement
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 = 1
for 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 + 1
else
self.Bullets = nil
end
end



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 this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!