As promised in previous post, here is another set of functions to operate with arrays. This time it is to do with Associative Arrays. In a nutshell, you have a key and a value pair you can store and then retrieve or modify it by key. As there is no dedicated associative array handling in Arma, it can be emulated. One way is to keep it in [[key1,val1],[key2,val2]…] format. However such approach, although visually pleasing, is pretty awkward to work with due to SQF array commands, not to mention multi-dimensional arrays are slowing down performance. So I’ve created a set of functions that handle 2 parallel arrays, one with keys [key1,key2...], one with respectful values [val1,val2...].
This will create an instance of associative array and return a string with reference to this instance. I wanted to be able to create thousands of arrays in split second if needed, so the reference needs to be 100% unique. Well, well, well, debug name for an object that is returned when you hint str _obj is pretty unique and safe. Creating a WeaponHolderSimulated will make a unique instance of an object and then delete the object instantly, perfect for a unique ID!
This function will add a (key, val) pair to an existing array indicated by array reference obtained from KK_fnc_assocArrayCreate function:
If you do not have array already created, you can create it on the fly with this function, by passing something to it as a reference. For example I can create an associative array linked to my player by passing netId of my player (netId is unique enough but MP only):
The function also returns array reference for convenience. It is worth mentioning that there could only be 1 unique key (case sensitive) in associative array, so if you try to add (key, val) pair and the key exists, you will simply overwrite the existing key value. If you do not want this to happen, you can always check for the existence of a key.
What is says on the tin. If key exists you will get true, or false if it doesn’t exist.
You can use this function to get the value of a key.
If you know for sure the key exists, then no problem. If not sure, you can either check for key existence with the KK_fnc_assocArrayKeyExists, or check if the returned result is not nil:
This will clear memory of (key, val) pair but will not resize the array. On successful operation it will return true, but if key does not exist it will return false.
Will clear memory occupied by array.
This will return all the keys of the array, including placeholders for deleted keys. To calculate the length of array, you can simply count the keys.
One thing I’d change would be the removal and not deletion of array elements. Might do it later if I can find an elegant way of doing it.
EDIT: KK_fnc_assocArrayAddKeyVal tweaked.
EDIT2: KK_fnc_assocArraySize changed to more useful KK_fnc_assocArrayAllKeys.
EDIT3: KK_fnc_assocArrayKeyExists optimised.