I am writing a program that loops through an array to check Boolean alarm variable statuses.
I want to dynamically generate the for-loop count integer to end the loop.
I have looked through Benchoff's Twincat 3 Documentation and can't find any generic SIZEOF()
functions to generate the array size, for example
nArraySize := SIZEOF(Array);
another thought is the Generate the Upper and lower bounds of the array to determine the size but I cannot find any functions to do this either.
You can't really determine the size like that, the SIZEOF returns number of bytes the variable occupies. You are missing one step, divide the array size (byte count) with the base type, to determine how many slices of data you have:
nArraySize := SIZEOF(array)/SIZEOF(array[0]) - 1;
and then you can call the for loop as
for i := 0 to nArraySize by 1 do
myArray[i] ...
This of course assumes your array starts at 0.
Upper and lower bounds can only be used on variable sized arrays. One way you could do something is have the array defined somewhere in your program, and then have a function or a method, that has the variable array as IN_OUT
parameter, as required by the variable arrays:
myArray : ARRAY[5..10] of ST_MyDataType;
F_DoSomething
VAR_IN_OUT
refArray : ARRAY[*] of ST_MyDataType
END_VAR
VAR
nIteration
END_VAR
FOR nIteration := LOWER_BOUND(refArray,1) to UPPER_BOUND(refArray,1) by 1 do
if refArray[nIteration].Something = TRUE then
...
END_FOR
and then call the function as is:
F_DoSomething(myArray);
One last way you could work is with memory access and pointers, but that gets a bit more complicated then, and is unsafe if not taken extra care of addresses.