2

How can assign a new variable to an array in TwinCAT?

in TwinCAT you can initialize all your array's argument directly for example for array a we can use:

a : ARRAY [1..3] OF INT := [3(0)];

or

a : ARRAY [1..3] OF INT := [0,0,0];

but if you want to assign the array in the main program(not initializing part) for example

a:=[2,8,5];

you will face this error tip: Unexpected array initialisation.

enter image description here

any help would be appreciated.

asys
  • 667
  • 5
  • 20
  • 1
    In the program you can access the array only per element, i.e. you will need 3 statements to fill the entire 3 element array; a[1]:=2;a[2]:=8;a[3]:=5; – owillebo Jun 16 '21 at 06:58
  • @owillebo this is just a simple example imagine it for n variables with different values one simple way is to use `for loop` but it's not interesting at all for over stack and etc. that is why I'm looking for another way. – asys Jun 16 '21 at 08:09
  • There is no other way to do this that I know of. Why can't you use a for loop? – Roald Jun 16 '21 at 15:57
  • 2
    At the cost of some additional memory you could declare a const array and initialize it with [2,8,5] giving it a clear name and use a for loop in the program to copy the data in to a. – owillebo Jun 17 '21 at 09:12
  • @Roald there are lots of reasons one of them is the force of management! – asys Jun 20 '21 at 04:03

1 Answers1

1

You cannot directly initialize arrays inside the program part.

That beeing said, the best option is porbably to define a constant containing the desired initialization values and then assigning the value of that constant to your array:

VAR 
    aiMyArray : ARRAY [1..2] OF INT;
END_VAR
VAR CONSTANT
    aiInitializerMyArrayOptionA : ARRAY [1..2] OF INT := [1,2];
    aiInitializerMyArrayOptionB : ARRAY [1..2] OF INT := [3,4];
END_VAR
IF bCondition THEN
    aiMyArray := aiInitializerMyArrayOptionA;
ELSE
    aiMyArray := aiInitializerMyArrayOptionB;
END_IF

The other option would be to manually initialize each index one by one which easily gets impracticale with decent array sizes:

IF bCondition THEN
    aiMyArray[1] := 1;
    aiMyArray[2] := 2;
ELSE
    aiMyArray[1] := 3;
    aiMyArray[2] := 4;
END_IF

Looping thorugh all elements and assigning values might be an option too. But that would only be usefull when the values are no arbitrary constatns but you are able to calculate the values from some formula.

Felix
  • 1,066
  • 1
  • 5
  • 22