band_delete() does not work properly

Started by srssmith92

srssmith92 Lv 1

I have a puzzle where I run the following test script. The puzzle is #322.

Half way through the list of deleting the bands I get the following error:

bad argument #1 to 'band_delete' (band index out of range)

In my most recent example, 25 of 51 are deleted. Failure on 26. Curious that this is half of the total.

I don't see how this can be. Foldit API gave the script the count and then the script runs through
that count.

– band create delete test

function create_a_band(start,finish)
band_add_segment_segment(start,finish)
end

function draw_bands(seg_list)
for i=1,#seg_list do
create_a_band(seg_list[i].start,seg_list[i].finish)
end
end

function create_seg_pairs(beg_seg, end_seg, stride)
local seg_list = {}

for i = beg_seg, end_seg do
	local seg_pair = {}

	seg_pair.start = i
	seg_pair.finish = i + stride
	seg_list[#seg_list+1] = seg_pair
end
return seg_list end

function delete_all_bands()
local band_count = get_band_count()
local loop
for loop = 1, band_count do
print("deleting band ", loop, " of ", band_count)
band_delete(loop)
end
end

seg_list = {}
g_segments = get_segment_count()

stride = 3
seg_list = create_seg_pairs(2,g_segments-stride-5,stride)

draw_bands(seg_list)

delete_all_bands()

Datstandin Lv 1

Ran into this somewhere, but unfortunately don't remember. Had to use index / 2 to get to the right position.

Tlaloc Lv 1

Not a foldit bug. The problem is in your script. You have the equivalent of this code:

for i=1,get_band_count() do
band_delete(i)
end

Explaining: you deleted band #1, then told it to delete band #2, and so forth. But band #2 became band #1 when you deleted it, so you really skipped the original band #2. The range you are looping has changed the moment you delete the first band. This is a classic problem in programming.

There are several ways around this:

1) Just do band_delete() with no arguments. This will delete all bands, so you don't need a loop.

2) Use this code, which deletes band #1 until there are no more bands:

while get_band_count() > 0
band_delete(1)
end

3) Use this code, which starts with the last band and loops toward the beginning. This solves the issue that the count changes as the bands are deleted, since the band you are deleting will always be the last one:

for i=get_band_count(),1,-1 do
band_delete(i)
end

I closed this. If you disagree for any reason, feel free to re-open it.