is there a way to iterate through a map?

V

ViceVersa

Guest
Im using a ds_map for a players weapon inventory, think like a final fantasy game, they can pickup and sell them, and have multiples of each. Im using a map because each weapon in the collection should at the very least have a name, and the count for how many you have.

Anyway, im trying to make a basic menu that will scroll through all the weapons you have, but I cant figure out how to get the element index for each element in the map.
 

Binsk

Member
Look up the function ds_map_find_first in the manual. Take note of the code example and how they iterate through the map.

As a side note, map data is stored in an unrecognizable order so I can't help but imagine you aren't going to get your items displayed in the order you want. You might consider using a ds_list or ds_priority to sort the map items so that you can shuffle them how you want.
 

FrostyCat

Redemption Seeker
Your standard pattern for looping through a map:
Code:
for (var k = ds_map_find_first(map); !is_undefined(k); k = ds_map_find_next(map, k)) {
  var v = map[? k];
  /* Use k, v here */
}
Note that maps in GM are implemented as hashtables, and thus does not always retain the order in which entries were inserted. If you need this ordering, you should keep a list of keys indicating the insertion order, parallel to the map. Then instead of the pattern above, just loop through the list.
 
V

ViceVersa

Guest
that makes sense thanks guys. I didnt know they didnt retain order like that, I ended up using lists instead, but thanks again!
 
Top