Jump to content

# [Beginners guide]: Arrays

## Recommended Posts

Thanks for that sel.

The reason i use it is actually not related to the alphabet, i simply used that as my example because I needed it to work with strings (as opposed to numeric values) and the alphabet was the easiest set of strings for the sake of showing me the methodology.

Thanks for your solutions, they look perfect :)

#### Share this post

##### Share on other sites
Using an alphabet will only allow 24 units

```alphaarray = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
_i=0;
{
_x setvariable ["letter",alphaarray select _i,true];
_i=_i+1;
} foreach allunits; ```

to retrieve the letter you need to use getvariable

`hint   (name_of_unit getvariable "letter")`

you could just assign a number

```_i=0;
{
_x setvariable ["number",_i,true];
_i=_i+1;
} foreach allunits; ```

to retrieve the number you need to use getvariable

`hint   str (name_of_unit getvariable "number")`

or a little of both

```_i=0;
{
_x setvariable ["string","man_" + str _i,true];
_i=_i+1;
} foreach allunits; ```

retrieve with

`hint   (name_of_unit getvariable "string")`

ok Ive tried this one. I get correct number every time so it works. What I hoped it would do is have something like yourunitname1,yourunitname2, and so on. What Id like to know. Is how can I set it up so say I want each unit and/or group is labeled in an array. Like for instance. I've got the allgroups as an array, but I'd like to name each individual groups with a variable. Like Alpha 1:1 would be grp1, alpha 1:2 would be grp2, alpha 1:3 would be grp3, and so on. Your code works, but I'd like to define groups or units with a variable in an array so I can call them through a loop. I hope that made sense. Thanks for you response in advance, also thanks for taking the time out to help explain how arrays work.

#### Share this post

##### Share on other sites

This piece of code will automatically create global variables and assign the respective groups to it:

```for "_groupIndex" from 1 to count allGroups do
{
call compile format ["group%1 = (allGroups select (%1-1));", _groupIndex];
};
```

So using the global variables will refer to the respective groups:

```group1 addWaypoint [_center, 0];  // is equal to: (allGroups select 0) addWaypoint [_center, 0];

_numCrew = count (crew group3); // is equal to: count (crew (allGroups select 2))
```

But to be honest I dont understand your last part, if you want to "label" your groups in order to loop through them, why not use allGroups and a forEach-loop in the first place?

#### Share this post

##### Share on other sites
This piece of code will automatically create global variables and assign the respective groups to it:

```for "_groupIndex" from 1 to count allGroups do
{
call compile format ["group%1 = (allGroups select (%1-1));", _groupIndex];
};
```

So using the global variables will refer to the respective groups:

```group1 addWaypoint [_center, 0];  // is equal to: (allGroups select 0) addWaypoint [_center, 0];

_numCrew = count (crew group3); // is equal to: count (crew (allGroups select 2))
```

But to be honest I dont understand your last part, if you want to "label" your groups in order to loop through them, why not use allGroups and a forEach-loop in the first place?

Thanks man I had to edited it a bit to give me what I was looking for, but I think this will work. as for foreachloop Ive used it and it worked for something else and I couldn't figure out how to do what you just tought me. lol BUT I had a program in LUA for OFP201. I wanted to see how this language differs in that area. I've got some knowledge of scripting, but its extremely limited. lol Thanks man I appreciate the help :)

P.S. I figured that last part was confusing on my last post sorry about that.

P.s.s hah didnt work like I'd hoped BUTTTT lol It helped me see what I wasn't seeing on foreach-loop, and was already using allGroups but couldn't extract other groups out at that time. now thanks to you I can extract even singular units. ;) Thanks again!

Edited by Mikey74

#### Share this post

##### Share on other sites

Hi, I figure this would be the best place to post my array related question as I doubt it merits its own thread :D

How exactly would I use the set command to subtract an element from an array? I seem to remember reading somewhere to use set [index, nil] or maybe null, I can't remember :confused:

For example, say I have this array

`[1, 2, 3, 4, 3, 5]`

And I wish to get rid of the second 3. From what I can gather from the wiki, using the - binary operator would return the array

`[1, 2, 4, 5]`

which is not what I want. So, how exactly is the set command used to delete elements?

#### Share this post

##### Share on other sites

Snip3r

```arry = [1, 2, 3, 4, 3, 5];
arry = arry - [arry select 4];```

Would be the simple way. Maybe its this

`arry  set [1,-4];`

. I too am learning arrays which brings me to my question.

Arrays take up memory correct? I have this code going and learned some what the setvariable command. example:

```_AISS_friends = [];
{if (((side _x) getFriend (side _commander) > 0.6) and !(_x in _AISS_friends)) then {_AISS_friends set [count _AISS_friends, _x]};}count allUnits;
_group setVariable ["Friends",_AISS_friends, true];```

NOW I've found so far the setvariable command works. BUT is it faster and does it take up less Memory than just _AISS_friends? IF so is there a way to delete the array _AISS_friends? I know I can clear it with just another

` _AISS_friends = [];`

BUT can I delete that?

Edited by Mikey74

#### Share this post

##### Share on other sites
Hi, I figure this would be the best place to post my array related question as I doubt it merits its own thread :D

How exactly would I use the set command to subtract an element from an array? I seem to remember reading somewhere to use set [index, nil] or maybe null, I can't remember :confused:

For example, say I have this array

`[1, 2, 3, 4, 3, 5]`

And I wish to get rid of the second 3. From what I can gather from the wiki, using the - binary operator would return the array

`[1, 2, 4, 5]`

which is not what I want. So, how exactly is the set command used to delete elements?

You just need to set the item you want to erase from the original array to any value which is unique in the array - as you already stated using the '3' would delete all threes, which is not desired.

So you have to set that item to any other value, objNull being the favorite case.

```_array = [1, 2, 3, 4, 3, 5];
_array set [4, objNull];
_array = _array - [objNull];```

You have to manually set the desired item to be erased, because there is no doable method to exclude duplicate items from erasion when using the binary operator '-'.

. I too am learning arrays which brings me to my question.

Arrays take up memory correct? I have this code going and learned some what the setvariable command. example:

```_AISS_friends = [];
{if (((side _x) getFriend (side _commander) > 0.6) and !(_x in _AISS_friends)) then {_AISS_friends set [count _AISS_friends, _x]};}count allUnits;
_group setVariable ["Friends",_AISS_friends, true];```

NOW I've found so far the setvariable command works. BUT is it faster and does it take up less Memory than just _AISS_friends? IF so is there a way to delete the array _AISS_friends? I know I can clear it with just another

` _AISS_friends = [];`

BUT can I delete that?

Okay, here's a "short" lesson about datatypes used in ArmAScript:

As this being a script language, there has to be some application interpreting and executing it - which is the game engine obviously. The game engine itself should be written in C(*), so you actually need to know the programming language to be able to really know which datatype takes how much memory.

But these considerations are useless, because a scripting language is there to abstract from any requirements of knowledge concerning memory, datatype handling etc.

Yes, arrays take up memory (afaik the most of memory any datatype takes in script languages), like every other variable you define in your script. Some may take memory just temporarily (local variables for instance), and others through the whole instance (I assume global variables).

But arrays are handled a bit different due to memory considerations: an ArmAScript array can take any size (well I doubt that one but let's believe that for now) of items dynamically during run time, which means the interpreter (the game engine) has to offer some abstract data type which allows dynamic allocation of memory AND offer the possibility to take any datatype as array items the script language supports, which isn't an easy thing to achieve at all.

So for every array you define in the script, there will be quite some memory allocation and managment going on in the background for that (I estimate multiple times of the memory a C(*)-array needs).

So let's examine an example:

```_myArray1 = [1,2,3];
_myArray2 = _myArray1;
_myArray3 = +(_myArray2);

_myArray2 set [3, 4];
_myArray2 = [5, 6, 7];
_myArray3 set [0, 0];
```

So what do you think the three arrays contain after execution? Let's take a deeper look:

_myArray1 is initialized with the numbers 1-3.

_myArray2 is a "copy" of _myArray1, but the more exact term would be a reference (which is just 4/8-Bytes). So _myArray2 is pointing to _myArray1, which is wanted because in most cases you don't really want to copy the content of arrays.

_myArray3 is actually a copy of _myArray2, which is a reference to _myArray1. This means _myArray3 is allocated the memory to hold the content of _myArray1.

In the lower part of the code, we manipulate the arrays:

The fourth item (zero based index!) of _myArray2 is set to 4, but because _myArray2 is just a reference, the actual change is being applied to _myArray1, resulting in [1,2,3,4].

After that _myArray2 is set with new items, and after this line _myArray2 ceases to be a reference and becomes an allocated array with the values [5,6,7].

In the end, the first item of _myArray3 is set to 0, resulting in [0, 2, 3]

So what did we learn with this code? Every array you assign to another variable is just a reference unless you explicitly mark to copy the array (binary operator '+').

How can this be applied to your question however? Well you're assigning a local array to an object (in your case an existing group). Normally you'd expect it to actually copy the content over to the object, but this would mean more memory allocation and the base class of the object to hold different abstract data types to be assignable through the setVariable-command.

Surprisingly enough even the setVariable command saves the reference of the array, not the contents of it.

So you could manipulate the array you assigned to your group afterwards and the changes will be mirrored into the variable you get with getVariable. This holds true for singleplayer though, I can't say that for sure for multiplayer (you're broadcasting the variable after all), because the reference of your variable is only valid in your enviroment (your local game), but isn't for others.

To answer your last question: you can't explicitly delete variables (and the allocated memory for it). But you can undefine a variable due to assingning nil to it.

When the last reference to that variable ceases to exist, the allocated memory will be freed for further use.

```_myArray1 = [1,2,3];
_myArray2 = _myArray1; // _myArray2 is referencing _myArray1

_myArray1 = nil; // _myArray1 is undefined here, so _myArray2 points to nothing, but it still references _myArray1
_myArray2 = [4, 5, 6]; // _myArray2 is initialized with another array, so there are no references to _myArray1 anymore
```

When and how the game engine decides to free allocated memory is not known to me and isn't even needed to be known by us scripters if the game engine handles everything right.

Edited by XxAnimusxX

#### Share this post

##### Share on other sites

ahhhhhh I was thinking way to hard on that. I wasn't sure if nil work with arrays. Thanks!!!! :) I eventually did away with the setvariable command on that array. It didn't work out quite as well as I expected. lol Thanks again XxAnimusxX

#### Share this post

##### Share on other sites

Hi,

got a little problem with an array here.

_anchorX=9961.4;

_anchorY=19351.6;

_objectsArray= [

["Land_HBarrier_1_F",[-3.08301,-0.207031,-0.309708],14.1034,1,0,[],"","",true,false],

["Land_HBarrier_1_F",[-2.98926,0.943359,0],184.672,1,0,[],"","",true,false],

...

];

hint "array created";

for "_i" from 0 to ((count _objectsArray)-1) do

{

_temp = (_objectsArray select _i);

_tempLoc = (_temp select 2);

_tempLoc set [1,(tempLoc select 1)+_anchorX];

_tempLoc set [2,(tempLoc select 2)+_anchorY];

_temp set [2, _tempLoc];

_objectsArray set [_i, _temp];

createVehicle (_objectsArray select _i);

};

hint "done";

What I'm trying to do:

I want to recreate what I grabbed with

"[getpos this, 100] call bis_fnc_objectsgrabber"

at exact same position.

I get "Array created" but it never survives the loop. Any ideas? :(

Edit:

Error found, these arrays aren't createVehicle arrays. This guide works: http://forums.bistudio.com/showthread.php?173396-Dynamic-Object-Compositions-(DoC)&p=2641626&viewfull=1#post2641626

Edited by mech

#### Share this post

##### Share on other sites

You can ignore, I see your looking at another thread now in A3 forum.

Are you sure your problem is with the array, it looks more like actual scripting issue.

If I'm reading it right your trying to reposition the objects by adding an offset.

Currently though your adding it to the direction also you have more elements in your array than createVehicle requires.

I think it will need to look like this ,

```_anchorX=9961.4;
_anchorY=19351.6;

_objectsArray= [
["Land_HBarrier_1_F", [-3.08301,  -0.207031,  -0.309708],14.1034,[],""],
["Land_HBarrier_1_F", [-2.98926,  0.943359,     0]            ,184.672,[],""]];

hint "array created";

for "_i" from 0 to ((count _objectsArray)-1) do
{

_temp = (_objectsArray select _i);
_tempLoc = (_temp select 1);
_tempLoc set [1,(_tempLoc select 0)+_anchorX];
_tempLoc set [2,(_tempLoc select 1)+_anchorY];
_temp set [1, _tempLoc];

_objectsArray set [_i, _temp];

// for debug
hint str (_objectsArray select _i);
sleep 2;

_obj createVehicle (_objectsArray select _i);

};
//hint "done";```

Edited by F2k Sel

#### Share this post

##### Share on other sites

Great! If that works, that would safe me a lot of work getting the BIS function to work. Tomorrow is scripting day, I will check it out and get back to you, thx mate!

#### Share this post

##### Share on other sites

I tried to find my answer in this thread but i probably went blind.

I have a script that save the position of a vehicle with

```_pos = getPosATL _obj;
```

that is saved to an array like this

```Position="[14557,16252.9,0.000980377]"
```

The saving part is done further down in the script

so before i save the position which is unknown to me

i want to set the third value(0.000980377) in this case to 1.

but for the discussion, how do a set any value(position within the array) in an array that isn't know to me without altering the other unknown values.

#### Share this post

##### Share on other sites
I tried to find my answer in this thread but i probably went blind.

I have a script that save the position of a vehicle with

```_pos = getPosATL _obj;
```

that is saved to an array like this

```Position="[14557,16252.9,0.000980377]"
```

The saving part is done further down in the script

so before i save the position which is unknown to me

i want to set the third value(0.000980377) in this case to 1.

but for the discussion, how do a set any value(position within the array) in an array that isn't know to me without altering the other unknown values.

```_pos set [2, 1]
```

Thank you =)

#### Share this post

##### Share on other sites
```_pos set [2, 1]
```

That worked fine and this was actually either here or in killzonekids tutorials but it took this for me to understand it so thanks again.

Now, if i just dont want to change any of the unknown values here

`Position="[14557,16252.9,0.000980377]"`

but add (1)to them so the third set would be

`Position="[14557,16252.9,1.000980377]"`

or any number i would like to subtract or multiply or add, is that possible with arrays.... dumb question i guess, there are a lot of magicians here =)

#### Share this post

##### Share on other sites
That worked fine and this was actually either here or in killzonekids tutorials but it took this for me to understand it so thanks again.

Now, if i just dont want to change any of the unknown values here

`Position="[14557,16252.9,0.000980377]"`

but add (1)to them so the third set would be

`Position="[14557,16252.9,1.000980377]"`

or any number i would like to subtract or multiply or add, is that possible with arrays.... dumb question i guess, there are a lot of magicians here =)

Just select the value, add/substract/multiple, and then insert the value again.

```_value = (_pos select 2) + 1;
_pos set [2, _value];

```

#### Share this post

##### Share on other sites

Here is a little function I created to shuffle an array. I use it to randomize arrays before some specific forEach cycles.

If someone needs it, feel free to use it.

```private ["_arr", "_curr_id", "_rnd_id", "_temp_val"];

_arr = _this select 0;

//diag_log format [">>> Array before shuffling > %1", _arr];

_curr_id = count _arr;

while {_curr_id != 0} do {
_rnd_id = floor random _curr_id;
_curr_id = _curr_id - 1;

_temp_val = _arr select _curr_id;

_arr set [_curr_id, _arr select _rnd_id];
_arr set [_rnd_id, _temp_val];
};

//diag_log format [">>> Array after shuffling > %1", _arr];
//diag_log format [">>>"];

_arr```

#### Share this post

##### Share on other sites

Hello,

I'm a bit confused over selecting from nested arrays, wellstuck for a few days now. I've read through the post and also KillzoneKids tutorials, the wiki also makes sense but nobody has the example below. I realise this is for an Arma 3 function but as I understand select hasn't changed and could find nothing relevant in the Arma 3 editing section.

This is one array from a list of similar arrays that are randomy selected and then use the BIS_fnc_setTask;

```_pMissionMogilevka = ["taskOne",true,["Capture all bases at Mogilevka","Capture Mogilevka","Objective"],[d_target_1,true],"ASSIGNED",1,true,true];
_pMissionGugovo = ["taskTwo",true,["Capture all bases at Gugovo","Capture Gugovo","Objective"],[d_target_2,true],"ASSIGNED",1,true,true];```

The code below will select a random objective and setTask

```_pMission_array = [_pMissionMogilevka,_pMissionChernogorsk] call BIS_fnc_selectRandom;
_pMissionCreate = [_pMission_array call BIS_fnc_setTask] call BIS_fnc_MP;```

This section is then used to get the object location and uses it to spawn in markers, enemy patrols etc. e.g. it will return a value of d_target_#

`_pMission = (_pMission_array select 3) select 0;`

This is the section I am having trouble with, the above works great, random target town is selected, markers and enemy are spawned in, the task appears for everyone.

However, as this is a TvT I need Victor/Loser parameters for task SUCCEEDED or FAILED, therefore I need to get the task ID to use later on in the script. The script below returns an error. The use of hint is just to let me know if it's pulling out the string.

```_pMissionId = _pMission_array select 0;
sleep 5;
hint ["%1",_pMissionId];```

For context this is the line that will use the variable

`_taskSucceeded = [[_pMissionID,"SUCCEEDED"] call BIS_fnc_taskSetState] call BIS_fnc_MP;`

Many thanks in advance

CptHammerBeard

#### Share this post

##### Share on other sites

Well, "_pMission_array" is a local variable and exists only in the scope where it was defined.

I assume the line "_pMissionId = _pMission_array select 0;" is being executed in another scope or script so the variable is undefined, hence the error.

Please be adviced that your use of BIS_fnc_MP seems to be false, you're just supplying a parameter. I never used that function before so I cannot say that for sure, but the BIKI-page says otherwhise: https://community.bistudio.com/wiki/BIS_fnc_MP

#### Share this post

##### Share on other sites

Thanks for reply Anim,

The code is as follows within the sqf. the variables _pMissionElektorvadsk and _pMissionPusta are defined within a seperate sqf. I know that _pMissionCreate works, as it sets the task accordingly, even for JIP. This has been tested in a dedicated server environment.

```//Call the next town to be captured
_pMission_array = [_pMissionElektrovadsk,_pMissionPusta] call BIS_fnc_selectRandom;

_pMissionCreate = [_pMission_array call BIS_fnc_setTask] call BIS_fnc_MP;  //setTask, without fnc_MP nothing works

_pMission = (_pMission_array select 3) select 0;  //this line is correct as without it the script would not know where to set the Task Marker, enemy spawns etc

_pMissionId = _pMission_array select 0; //I am convinced this line is returning a value of the entire array```

Re call BIS_fnc_MP;, without that the BIS_fnc_setTask doesn't broadcast to all players, it also works with JIP.

Many thanks again

Cheers

CptHammerBeard

Edited by CptHammerBeard

#### Share this post

##### Share on other sites

A friend of mine wants to separate data in an array so that instead of the getPos player; returning a position like this [1891.62,5713.53,0.00143909]

It will instead return like this

```X: 1891.62
Y: 5713.53
Z: 0.00143909```

Is this the best way to do it?

```_xPos = getPos player select 0;
_yPos = getPos player select 1;
_zPos = getPos player select 2;

hint format["X: %1 \n Y: %2 \n Z: %3",_xPos, _yPos, _zPos];```

Edited by ColinM9991

#### Share this post

##### Share on other sites

Wow, this thread has been amazing to read, Soooo helpful for getting a beginner, in arrays, up to speed and showing the basics as well and the advanced stuff. hats of to you guys.

#### Share this post

##### Share on other sites

Cool thread i have a question..

```missingaddons = ["air_c130j","blastcoretracers"]
[missingaddons,"and some other variables"] call showdialog;```

```_missing = _this select 0;
"and some other variables"
_debug = "http://dev.taskforce47.de/missingAddons.php?map=" + _map + "&mission=" + _mission + "&player=" + _player + "&missing=" + (format _missing);```

That would work

```_debug = "http://dev.taskforce47.de/missingAddons.php?map=" + _map + "&mission=" + _mission + "&player=" + _player + "&missing=" + (_missing select 0)+,+(_missing select 1);
```

But _missing could also be:

`missingaddons =["air_c130j","burnes_m1a2_public","bwa3_tracked","bwa3_units","cse_sys_advanced_interaction","cse_sys_backblast","cse_sys_equipment","cse_sys_gestures","cse_sys_groups","cse_sys_ieds","cse_sys_logistics","cse_sys_medical","cse_sys_misc","cse_sys_weaponrest","dar_mtvr","ewk_m1151","hafm_arma2_helis","js_jc_fa18","kyo_mh47e","peral_a10","rav_lifter_a3","task_force_radio_items","cba_xeh","blastcoretracers","us_helo_hmds_kimi"]`

#### Share this post

##### Share on other sites
Cool thread i have a question..

```missingaddons = ["air_c130j","blastcoretracers"]
[missingaddons,"and some other variables"] call showdialog;```

```_missing = _this select 0;
"and some other variables"
_debug = "http://dev.taskforce47.de/missingAddons.php?map=" + _map + "&mission=" + _mission + "&player=" + _player + "&missing=" + (format _missing);```

That would work

```_debug = "http://dev.taskforce47.de/missingAddons.php?map=" + _map + "&mission=" + _mission + "&player=" + _player + "&missing=" + (_missing select 0)+,+(_missing select 1);
```

But _missing could also be:

`missingaddons =["air_c130j","burnes_m1a2_public","bwa3_tracked","bwa3_units","cse_sys_advanced_interaction","cse_sys_backblast","cse_sys_equipment","cse_sys_gestures","cse_sys_groups","cse_sys_ieds","cse_sys_logistics","cse_sys_medical","cse_sys_misc","cse_sys_weaponrest","dar_mtvr","ewk_m1151","hafm_arma2_helis","js_jc_fa18","kyo_mh47e","peral_a10","rav_lifter_a3","task_force_radio_items","cba_xeh","blastcoretracers","us_helo_hmds_kimi"]`

So, what's the question here?

#### Share this post

##### Share on other sites

How do i archive the array in a string parsed as a above stated here

(_missing select 0)+,+(_missing select 1)

because if select 10 for example is not returned it is an error Or ?

## Please sign in to comment

You will be able to leave a comment after signing in

Sign In Now

×

• Clubs