swarm-support
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Swarm-Support] Problem with a list index...I think?


From: Steven Hamblin
Subject: [Swarm-Support] Problem with a list index...I think?
Date: Fri, 5 Oct 2007 20:46:27 -0400

Hello,

I'm new to Swarm, and I'm using it to write the code for a model I'm playing around with.  I've just spent the last day trying to track down a really persistent bug in the program, and I finally solved the problem.  The thing that vexes me is that I can't understand *why* I solved the problem.  

Background:  I've been adapting the code from the tutorial (simpleObserverBug series).  I've modified the FoodSpace in that program to use an object where the food patches are instead just an integer value.  To store the patches, I'm using a List.  If the patches deplete I remove them, so I've added a killPatches method to the FoodSpace which gets called by the modelSwarm schedule.  killPatches implements a pretty simple idea:  it iterates through the list of patches, checking each patch to see if the remaining food there is less than or equal to 0.  If it is, it removes the patch from the list.  Here's the original code I had:

patchIndex = [patchList begin: [self getZone]];
for (currentPatch = [patchIndex next]; [patchIndex getLoc] == Member; currentPatch = [patchIndex next]) {
if ([currentPatch getFood] <= 0) {
[patchIndex remove];
}
}
[patchIndex drop];

I cribbed the for loop from the docs online.  However, every time I ran this, it would kill a certain number of the patches and then spit out an error ("nil receiver for getFood") and come to a crashing halt.  Core dumped everywhere.  It wasn't pretty, I'm telling ya.  I used gdb to trace the execution, but I'm new with gdb and I couldn't get too much out of it beside the fact that after the program executed the [patchIndex remove] statement, the next call to getFood when the loop ticked over would immediately throw everything off the rails.  

All right.  So I banged my head for a while, and on a lark, tried simplifying things by using the other loop structure I found in the docs:

patchIndex = [patchList begin: [self getZone]];
while ((currentPatch = [patchIndex next]) != nil) {
if ([currentPatch getFood] <= 0) {
[patchIndex remove];
}
}
[patchIndex drop];

And ... hallelujah!  It works perfectly.  But I ask you now, can anyone give me any clue as to *why* it works?  Is it some way in which the two different loops iterate through the List?  Or is it probably something more subtle, maybe a heisenbug somewhere else in my code?  

Thanks for your time!


Cheers,

Steven Hamblin
-- 
Ph.D Student
Département de Sciences Biologiques
Université du Québec à Montréal


reply via email to

[Prev in Thread] Current Thread [Next in Thread]