fn_setToPairs.sqf 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. Author: Jiri Wainar
  3. Modified by: Gundy
  4. Description:
  5. Sets an item in pair array to given value.
  6. Remarks:
  7. Works similar to the BIS_fnc_addToPairs but it doesn't try to add values. It just overwrites the volue if the key already exists.
  8. Example:
  9. [["apple",3],["pear",10]] = [[["apple",3],["pear",2]],"pear",10] call BIS_fnc_setToPairs;
  10. */
  11. private ["_pairs","_key","_value","_index"];
  12. _pairs = [_this,0,[],[[]]] call bis_fnc_param;
  13. _key = [_this,1,"",[""]] call bis_fnc_param;
  14. _value = [_this,2,1] call bis_fnc_param;
  15. _index = -1;
  16. {
  17. if (typeName _x != typeName []) exitWith
  18. {
  19. ["Every item in the pair array must be an array!"] call BIS_fnc_error;
  20. _index = -2;
  21. };
  22. if (count _x != 2) exitWith
  23. {
  24. ["Pair array must contain exactly 2 items, key and value!"] call BIS_fnc_error;
  25. _index = -2;
  26. };
  27. if (isNil{_x select 0}) exitWith
  28. {
  29. ["Key cannot be nil!"] call BIS_fnc_error;
  30. _index = -2;
  31. };
  32. if (typeName(_x select 0) != typeName "") exitWith
  33. {
  34. ["Key must be a string!"] call BIS_fnc_error;
  35. _index = -2;
  36. };
  37. if (isNil{_x select 1}) exitWith
  38. {
  39. ["Value cannot be nil!"] call BIS_fnc_error;
  40. _index = -2;
  41. };
  42. if (_key == (_x select 0)) exitWith
  43. {
  44. _index = _forEachIndex;
  45. };
  46. }
  47. forEach _pairs;
  48. //error occured, exit
  49. if (_index == -2) exitWith {_pairs};
  50. //key not found, add the new entry
  51. if (_index == -1) then
  52. {
  53. _pairs pushBack [_key, _value];
  54. }
  55. //key found, overwrite the existing entry
  56. else
  57. {
  58. _pairs set [_index, [_key, _value]];
  59. };
  60. _pairs