How to avoid array out of range ?

 

Hello Everyone 
How to deal with or handle/avoid the array out of range error here :


      for(int i=0; i<=ObjectsTotal()-1; i++)
        {
         string objName = ObjectName(0,i);
         if(StringFind(objName,"Last#")>=0)
           {
            string tempval= objName;
            string temtext= ObjectGetString(0,objName,OBJPROP_TEXT);

            StringReplace(tempval,"Last#","");
            int tempnum = (int)(tempval);
            for(int k=tempnum; k>=tempnum-20; k--)
              {
                
               if(
                  RBuffer1[k] != EMPTY_VALUE)      
                 {
                  ObjectDelete(0,objName);
                  DrawText("Last#"+tempnum,Time[tempnum],Low[tempnum],temtext+"_0","Arial",9,clrWhite);
                  break;

                 }
               else
                  if(RBuffer2[k] != EMPTY_VALUE)    
                    {
                     ObjectDelete(0,objName);
                     DrawText("Last#"+tempnum,Time[tempnum],Low[tempnum],temtext+"_1","Arial",9,clrWhite);
                     break;
                    }
              }
           }
        }

I am sure there is something wrong with my logic but cant figure out what exactly , and the indicator works fine on some timeframes but on 2 ,3 timeframes it throws the error array out of range
the highlighted part is where I am receiving the error.


 
I don't know exactly what is going on due to lack of information, but it is very likely that the value of k is going negative and RBuffer1[k] or RBuffer2[k] is experiencing an array out of range error.