I can’t picture how that error is even possible with the expression, as written, because if the expression detects no keyframes, it would fail on the previous line and complain about there being no keyframe number 1. In any case, you could defend against the error message by encasing the the whole thing in a test for two or more keyframes, like this:
if (numKeys > 1){
sampleSize = [1,1];
L = thisComp.layer("Alpha Scale");
P = L.fromComp(toComp(anchorPoint));
lum = rgbToHsl(L.sampleImage(P,sampleSize/2,true,time))[2];
t = 0;
t1 = key(1).time;
t2 = key(numKeys).time;
if (lum == 1){
t = thisComp.frameDuration
while ((t < t2 - t1) && t <= time){
lTemp = rgbToHsl(L.sampleImage(P,sampleSize/2,true,time-t))[2];
if (lTemp < 1){
t -= thisComp.frameDuration;
break;
}
t += thisComp.frameDuration;
}
}
valueAtTime(t1 + t);
}else
value