Removing an item from a dynamic array
-
Hello everyone,
I’m currently working on a project that has a dynamic array. To be more specific its a matrix array where one dimension is dynamic.
array sprites[][6]
Now my question,
I’d like to create a stack of sprites. That way I can keep track of the size of sprites.
len(sprites[i])
Is there a way to remove an item from a given index from an array lowering its size?
I saw there’s a seudo linked list example in the forum. If I can’t get this working I was thinking of going that route.
Any help would be appreciated.
-
There's not a built-in way to resize an array, but implementing a custom function to do it isn't too difficult -- you'll need to create a new array with one fewer elements than the original array and then copy the data into the new array. For example:
// Removes item at _idx from _arr. function remove(ref _arr, _idx) array newArr[len(_arr) - 1] var offset = 0 var i for i = 0 to len(newArr) loop if i == _idx then offset = 1 endif newArr[i] = _arr[i + offset] repeat return newArr
-
Thanks that is exactly what I need. Here’s a follow up question. How would this function call look like?
old_array = remove(old_array, index)
Or am I not able to reassign the array?
I would test this myself but I don’t access to my Switch right now. -
@linser22 Yes, that's correct -- it's okay to overwrite the original array.
Alternately, if you know you're always going to be overwriting the original, you could even do the reassignment inside of the function by adding the line
_arr = newArr
at the end of the function, in which case the function could be called withremove(old_array, index)
. -
You are a life saver. I spent more time than I’d like to admit on this. Now, I’m so excited to get back on this project. Thank you very much!
-
This is what I ended up going with it’s a little messy but I’ll put it here incase it’s helpful to anyone else. I’m working with sprites so I believe I can’t just sprite[0] = sprite[1]. If you can I haven’t been able to get it to work.
Thanks again.function remove(ref o_array, index) array n_array[len(o_array) - 1] var offset = 0 var i for i = 0 to len(n_array) loop if i == index then offset = 1 endif n_array = createSprite() setSpriteImage( n_array[i], block_image ) setSpritelocation( n_array[i], getSpriteLocation( o_array[ i + offset ] ).x, getSpriteLocation( o_array[ i + offset ] ).y + ( offset *8 )) setSpritecolor( n_array[i], getSpriteColor( o_array[ i + offset ] ) ) removeSprite( o_array[i] ) repeat removeSprite(o_array[ len(o_array) - 1 ] ) return n_array