Hi,
Can someone explain what i am doing wrong here...
I have 2 nested FOR loops
top is the shots fired existing on screen the second are the enemies to boxcoll against...
I can get the DIMDEL to work on the enemies but not the bullets and now getting array out of DIM array error
FUNCTION checkhits:
FOR sh = 0 TO LEN(shots[])-1
FOR en = 0 TO LEN(invader[])-1
IF BOXCOLL(shots[sh].x,shots[sh].y,32,32,invader[en].x,invader[en].y,32,32)
DIMDEL invader[],en
DIMDEL shots[],sh
DEBUG sh
ENDIF
NEXT
NEXT
ENDFUNCTION
Guys, i think i solved it ... but not sure if my method is "best practice"
Anyhow for others will similar nesting array issues...here's my solution...
FUNCTION checkhits:
FOR sh = 0 TO LEN(shots[])-1
remshot = -1
FOR en = 0 TO LEN(invader[])-1
IF BOXCOLL(shots[sh].x,shots[sh].y,32,32,invader[en].x,invader[en].y,32,32)
DIMDEL invader[],en
remshot = sh
DEBUG sh
ENDIF
NEXT
IF remshot<>-1 THEN DIMDEL shots[],remshot
NEXT
ENDFUNCTION
Basically i make sure I dont remove the shot too soon in the loop...I think that was the issue.
Your workaround is correct, but after you you delete an item from the array you need to DEC the Index, so you should add DEC sh
after the DEBUG line. This will avoid skipping one entry.
Generally you should never DIMDEL/REDIM etc. inside an loop of that array. Or at least you need to be really careful. Using FOREACH and DELETE could also help you.
Instead of your workaround you should also be able to use the BREAK command this should work too (untested) and look a bit more elegant.
I always sometime ago use for next, but it´s more easy for read and pick your code use foreach
I like FOREACH too...but tracking the index of the array is a problem using a DIMDEL etc.
Is the an index method i am missing for FOREACH?
You can make somethinh like
in the type put something like
index
and then in :
FOREACH item in array[]
item.index
//or a veriable
inc something
delete item or another things
next
You do not need an index to delete inside FOREACH, just use DELETE.
When I have to delete an element in a array while I'm in a loop, I begin the search from the end to the beginning of the array. This way if you delete an element you don't walk in an invalid position. For example:
FOR i = LEN(enemies[])-1 to 0 step -1
IF some_condition
DIMDEL enemies[], i
ENDIF
NEXT //i
Another solution if you want to delete many elements is mark the elements you want to delete with a field (1/0) or pushing in a index array, and deleting all the marked elements at the end of the search loop.
Thanks Hardyx / kanonet
Like those option.