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.

5
  • 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; Commented Jun 16, 2021 at 6: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. Commented Jun 16, 2021 at 8:09
  • There is no other way to do this that I know of. Why can't you use a for loop? Commented Jun 16, 2021 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. Commented Jun 17, 2021 at 9:12
  • @Roald there are lots of reasons one of them is the force of management! Commented Jun 20, 2021 at 4:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.