fn_getFromPairs.sqf 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. Author: Jiri Wainar, modified by Gundy to fix return of "nil" (line 63), see http://feedback.arma3.com/view.php?id=20643
  3. Description:
  4. Searches the associative array for the 1st occurance of the key string and returns the value associated with it.
  5. Syntax:
  6. _value = [_associativeArray:array,_key:string,_defaultValue] call cTab_fnc_getFromPairs;
  7. Example:
  8. 2 = [[["apple",3],["pear",2]],"pear"] call cTab_fnc_getFromPairs;
  9. Returns:
  10. * if found: value stored under the key
  11. * if not found: nil or _defaultValue
  12. */
  13. private ["_pairs","_key","_default","_value"];
  14. _pairs = [_this,0,[],[[]]] call bis_fnc_param;
  15. _key = [_this,1,"",[""]] call bis_fnc_param;
  16. if (count _this > 2) then
  17. {
  18. _default = [_this,2] call bis_fnc_param;
  19. }
  20. else
  21. {
  22. _default = nil;
  23. };
  24. {
  25. if (typeName _x != typeName []) exitWith
  26. {
  27. ["Every item in the pair array must be an array!"] call BIS_fnc_error;
  28. };
  29. if (count _x != 2) exitWith
  30. {
  31. ["Pair array must contain exactly 2 items, key and value!"] call BIS_fnc_error;
  32. };
  33. if (isNil{_x select 0}) exitWith
  34. {
  35. ["Key cannot be nil!"] call BIS_fnc_error;
  36. };
  37. if (typeName(_x select 0) != typeName "") exitWith
  38. {
  39. ["Key must be a string!"] call BIS_fnc_error;
  40. };
  41. if (isNil{_x select 1}) exitWith
  42. {
  43. ["Value cannot be nil!"] call BIS_fnc_error;
  44. };
  45. if (_key == (_x select 0)) exitwith
  46. {
  47. _value = _x select 1;
  48. };
  49. }
  50. forEach _pairs;
  51. if (isNil "_value") exitWith {if (isNil "_default") then {nil} else {_default}};
  52. _value