question about JFormMap.allKeys(map)

23 views
Skip to first unread message

Jim Kaiser

unread,
Apr 10, 2015, 8:52:04 PM4/10/15
to jcontain...@googlegroups.com
Alright, I have another question about JFormMap. If I call

mkeys = JFormMap.allKeys(map)

I understand that a new array is created which holds all of the keys in map. Am I correct that subsequent changes made to map, like the addition or removal of keys, will not have any effect on the array mkeys? I assume this is true, but want to verify.

In my particular case, I have a cloak spell that dynamically attaches a script to NPCs. When the script runs OnEffectStart(), the actor is added as a key to a map of NPCs under the effect (I'm using a map so that each actor is the key to a separate array of values associated with the actor). When the script runs OnEffectFinish(), the actors are removed from the map. Multiple threads may add or remove NPCs at various times. However, I occasionally need to iterate over the map in a separate script and run some code for some of the NPCs. In these situations, I would like to use JFormMap.nextKey(map), but because of the possibility of other threads removing keys while I am in the middle of iterating over the map, I am concerned that I may not actually reach all of the keys. For example, if I run code like the following:

Form key = JFormMap.nextKey(map)
Form nkey
while mkey
  nkey = JFormMap.nextKey(map, key)
  dosomething
  key = nkey
endwhile

and it happens that nkey is removed from map by some thread while my loop is in the middle of dosomething, then the next call to JFormMap.nextKey(map, key) will return endKey (default is none), and I will not iterate through the rest of the map. So, my current thinking is that I should first copy all of the keys into an array, and then iterate over the array so that I am sure to reach everything. The revised code will look like this:

int keys = JFormMap.allKeys(map)
int index = JArray.count(keys)
Form key
while index
  index -= 1
  key = JArray.getForm(keys, index)
  dosomething()
endwhile

Does this seem like a reasonable approach?

silverice

unread,
Apr 11, 2015, 6:01:37 AM4/11/15
to Jim Kaiser, jcontain...@googlegroups.com
> I understand that a new array is created which holds all of the keys in map. Am I correct that subsequent changes made to map, like the addition or removal of keys, will not have any effect on the array mkeys? I assume this is true, but want to verify.

It's absolutely new array, not connected to its map, so no effect

> Does this seem like a reasonable approach?

Seems reasonable, you may also need to retain the keys if iteration takes some notable amount of time

Reply all
Reply to author
Forward
0 new messages