Diff

util/indexedbheap.lua @ 6151:a34a14054532

util.indexedbheap: Fix a possible traceback when removing the last item.
author Waqas Hussain <waqas20@gmail.com>
date Wed, 23 Apr 2014 11:38:34 -0400
parent 5876:f62ad84811df
child 8382:e5d00bf4a4d5
line wrap: on
line diff
--- a/util/indexedbheap.lua	Wed Apr 23 00:23:46 2014 +0200
+++ b/util/indexedbheap.lua	Wed Apr 23 11:38:34 2014 -0400
@@ -113,23 +113,27 @@
 	k = _percolate_down(self.priorities, k, self.ids, self.index);
 end
 function indexed_heap:remove_index(k)
-	local size = #self.priorities;
+	local result = self.priorities[k];
+	if result == nil then return; end
 
-	local result = self.priorities[k];
 	local result_sync = self.ids[k];
 	local item = self.items[result_sync];
-	if result == nil then return; end
-	self.index[result_sync] = nil;
-	self.items[result_sync] = nil;
+	local size = #self.priorities;
 
 	self.priorities[k] = self.priorities[size];
 	self.ids[k] = self.ids[size];
 	self.index[self.ids[k]] = k;
+
 	t_remove(self.priorities);
 	t_remove(self.ids);
 
-	k = _percolate_up(self.priorities, k, self.ids, self.index);
-	k = _percolate_down(self.priorities, k, self.ids, self.index);
+	self.index[result_sync] = nil;
+	self.items[result_sync] = nil;
+
+	if size > k then
+		k = _percolate_up(self.priorities, k, self.ids, self.index);
+		k = _percolate_down(self.priorities, k, self.ids, self.index);
+	end
 
 	return result, item, result_sync;
 end