LoginLogin

Adding elements to a middle of an array

Root / FAQs / [.]

SaladFingersCreated:
How would I add a string in the middle of my string array?

Here's the function I use:
DEF INSERT ARRAY[],POS%,VALUE
 UNSHIFT ARRAY,VALUE 'This is just to make the array longer. I use VALUE since it will be the same variable type as the array.
 COPY ARRAY,ARRAY,1,POS% 'Moves all the elements before POS% 1 space to the left.
 ARRAY[POS%]=VALUE 'Add the new value.
END

Thanks very much! Is there a function to remove an element from the middle of an array? I tried making my own version using SHIFT but did not turn out so well.

Thanks very much! Is there a function to remove an element from the middle of an array? I tried making my own version using SHIFT but did not turn out so well.
Yeah, let me see if I can find it (Turns out I used it in the same program as the first one)
DEF REMOVE ARRAY[],POS%
 COPY ARRAY,POS%,ARRAY,POS%+1,LEN(ARRAY)-(POS%+1) 'move all elements after POS% 1 space left.
 EAT POP(ARRAY) 'remove the last element.
END
You'll need an EAT function, like
DEF EAT SAND END
It might be slightly faster to do:
DEF REMOVE ARRAY[],POS%
 COPY ARRAY,POS%,ARRAY,POS%+1,LEN(ARRAY)-(POS%+1) 'move all elements after POS% 1 space left.
 IF POP(ARRAY) THEN:ENDIF'remove the last element.
END