code of the Ninja();

// in search of swift, efficient, and invisible code

2013-09-27

Using Strings as Keys in Maps (Game Maker)

Hello, Code Ninjas. This post will be somewhat brief. I discovered a neat thing about Game Maker's map data structures that wasn't made clear in the help file, although (if you dig deep enough) the new Game Maker Studio documentation mentions it without drawing attention to it. If you don't know about it already, it could be quite useful.

Basically, the neat thing is this: The keys (as well as the values) of key/value pairs in a ds_map can be strings as well as real numbers, e.g. the following is valid:

This gives one a lot of power over merely using reals, so you'd think that the documentation would brag about it; perhaps it was assumed to be obvious. It wasn't obvious to me. I gave it a try on a whim after a bout of Javascript programming which made me think of it, and it just happened to work.

Now if you are wondering how string keys are treated by functions such as ds_map_find_first(), ds_map_find_next(), etc. it's pretty simple - they are considered alphabetically. Where the help file talks about these functions as returning the "smallest" key or the "next largest" key, which makes sense in terms of real numbers, you can substitute "earliest alphabetically" or "next in alphabetical order". For example, "a" would be a "smaller" key than "b".

The alphabetisation is case sensitive and is strict about punctuation and numbers, so it won't always behave intuitively. For example, if you add the keys "1", "2", and "10", then "10" will be considered "smaller" than "2". Uppercase letters are considered "smaller" than lowercase, as well.

Finally, if you have a mix of real keys and string keys, all real keys are considered "smaller" than all string keys. A real key of 4000 is "smaller" than a string key of "0".

Hopefully I'm not just super clueless and this was all totally obvious from the get go, and somebody benefits from me pointing it out. :)

Happy coding!