Edit: You aren't only trying to restack things into slot 4 are you? Because if so then the rest of this post doesn't really apply.
Edit 2: Our code is essentially the same now that I look again except that I put the turtle.select in a different place (first for loop rather than second, which would actually make a pretty serious speed difference when you consider that selecting takes longer than comparing or transfering) and I added in a few speed improvements. Also, you are trying to do sel(B ) rather than sel(b ), but since you got no errors I'm assuming that you made a typo transfering to the forum.
Edit 3: I did some speed tests, and this code:
for i=1,16 do
if turtle.getItemCount(i) > 1 then
turtle.select(i)
turtle.drop()
end
end
is faster (by 5 seconds actually), even when I combine the drop into the function as I do below. So that would probably be your best bet here.
Oops! Didn't really mean to post this cause I wasn't finished - just accidentally hit enter and it submitted. But anyway, this is my method of restacking. To be honest though, I feel like it would just be faster to dump directly into an ender chest because this way you have to cycle through the turtle's inventory twice as opposed to the once that you would do with a regular dump.
local function restack()
for x=1,16 do
if turtle.getItemCount(x) < 64 then
turtle.select(x)
for y=x+1,16 do --Avoids testing the same slot
turtle.transferTo(y) --It's actually not necessary to compare items - if it's able to transfer it will do so. This cuts down on the time of checking that they are the same and then transfering.
end
else
turtle.select(x)
turtle.drop() --Incorporates the drop into the restack function so that it's faster.
end
end
end
Also, is the turtle digging blocks itself or are items be inserted by users? Because if the former, then there would be no need for a restack.