Page 1 of 1

DeleteMapElement while iterating with ForEach

Posted: Tue Mar 21, 2017 10:08 am
by Xanos
What is the best method to delete map elements while being in a ForEach map() loop?
Example code, that is not working:

Code: Select all

Global NewMap test()

For i = 0 To 9
  r = Random(100)
  test(Str(r)) = r
Next


ForEach test()
  Debug "check element "+MapKey(test())
  If test() > 50
    DeleteMapElement(test(), MapKey(test()))
  EndIf
Next

Debug "---"

ForEach test()
  Debug MapKey(test())
Next
As soon as the first element is deleted, the ForEach loop just exists.

Re: DeleteMapElement while iterating with ForEach

Posted: Tue Mar 21, 2017 10:14 am
by Josh

Code: Select all

Global NewMap test()

For i = 0 To 9
  r = Random(100)
  test(Str(r)) = r
Next


ForEach test()
  Debug "check element "+MapKey(test())
  If test() > 50
    DeleteMapElement(test())
  EndIf
Next

Debug "---"

ForEach test()
  Debug MapKey(test())
Next

Re: DeleteMapElement while iterating with ForEach

Posted: Tue Mar 21, 2017 10:17 am
by Xanos
So in short, it is not possible to delete MapElements by stating their "Key$" in a ForEach?
Unfortunately, I have to rewrite a bunch of code to get around this in the real project (obviously not the short example code).

Re: DeleteMapElement while iterating with ForEach

Posted: Tue Mar 21, 2017 10:53 am
by Josh
Xanos wrote:So in short, it is not possible to delete MapElements by stating their "Key$" in a ForEach?
Help readers know more :mrgreen:
Help wrote: DeleteMapElement()
If the optional 'Key$' parameter is specified then there will be no more current element after this call.

Re: DeleteMapElement while iterating with ForEach

Posted: Tue Mar 21, 2017 6:55 pm
by normeus
use push and pop: *EDIT working code with push and pop

Code: Select all

Global NewMap test()

For i = 0 To 9
  r = Random(100)
  test(Str(r)) = r
Next

ForEach test()
  Debug MapKey(test())
Next

ForEach test()

  PushMapPosition(test())
  While NextMapElement(test())
    If test() > 50
      DeleteMapElement(test())
    EndIf
  Wend
  
  PopMapPosition(test())
Next
; "--- NECESSARY EVIL because we skipped first element do test on first again"
ResetMap(test())
NextMapElement(test())
If test() > 50
  DeleteMapElement(test())
EndIf

Debug "---"

ForEach test()
  Debug MapKey(test())
Next
Norm.

Re: DeleteMapElement while iterating with ForEach

Posted: Wed Mar 22, 2017 11:45 am
by Josh
normeus wrote:use push and pop
No need to use push and pop. Like I wrote in my example, only delete the second parameter in 'DeleteMapElement'

Re: DeleteMapElement while iterating with ForEach

Posted: Wed May 31, 2017 2:20 pm
by Xanos
Not using the second argument was not an option (at least not easily done), so pop & push are valid solutions for this problem :)