Skip to main content
GameDev.net gamedev.net
🔒 Locked

Lua Question

Started by DrEvil Nov 18, 2005 at 4:13 PM 3 replies 750+ views
Original Post
DrEvil
DrEvil
I'm not a lua pro, but I can't find any specific references about lua tables that covers this question so I'll ask here.

for key, actor in actorlist do
	if actor.timeToDelete < gameTime then
		actorlist[key] = nil
	end
end


I realize it's valid to remove a value from a lua table by setting it to nil, but it seems potentially unsafe to do it within a for loop like this. Does anyone know for sure, and/or could anyone provide references that say one way or the other? Thanks.
DrEvil
DrEvil
Nobody knows if this is safe or not? Does nilling a table element like this in a (for key, actor) invalidate the loop or the internal iterator or whatever? The reason I ask is because in an app we use, we were doing something similar and for some reason were occasionally getting infinite loops. Instead of just nilling though there was a function call before the entry was nilled so it was clear that the script was infinite looping within that specific for loop because the native function was being called constantly.
Kylotan
Kylotan
The iteration uses the previous value when finding the next value in the table to give you. So nuking the previous value may well give you problems. I would think it much more likely to kick you out of the loop prematurely than to loop infinitely however. This will be defined in the table module implementation, as the behaviour can differ depending on what you're iterating over.
Witchcraven
Witchcraven
In situations like that when I am lazy, instead of deleting the elemt in that loop, I add its index to a "deletion" array. After that loop is done, I go through the deletion array, and delete from the original array the stored indices. I usually use it for debugging, then find a better solution later.
--------------------------I present for tribute this haiku:Inane Ravings OfThe Haunting JubilationA Mad Engineer©Copyright 2005 ExtrariusAll Rights Reserved

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.