SIZE — Size In Elements
SIZE is the Structured Text instruction in rungs.dev that counts the elements of an array tag and stores the count in a DINT tag, so loops never hardcode an array's length.
Counts the elements of an array tag and stores the count in a DINT tag. Modeled on the
SIZE instruction in Logix 5000® controllers.
The point of SIZE is to keep the array's length out of your logic. A loop written
against a hardcoded TO 11 silently breaks the day someone resizes the tag to 20
elements; a loop written against a SIZE result keeps working.
SIZE(Samples, 0, Wrk_Count);After this statement, Wrk_Count holds the number of elements in Samples — for an
array created with size 12, that's 12 (elements Samples[0] … Samples[11]).
Operands
| Name | Type |
|---|---|
array | an array tag of any data type |
dimension | the literal 0 |
destination | DINT tag or DINT array element |
array is the bare array tag — no index. dimension asks which dimension to measure;
rungs supports single-dimension arrays only, so it must
be the literal 0 (the first and only dimension).
Worked Example
Average an array without ever hardcoding its length:
SIZE(Samples, 0, Wrk_Count);
Wrk_Sum := 0;
FOR Wrk_Index := 0 TO Wrk_Count - 1 DO
Wrk_Sum := Wrk_Sum + Samples[Wrk_Index];
END_FOR;
Out_Average := Wrk_Sum / Wrk_Count;Resize Samples in the tag editor and the loop follows along — no code change.
Rules
-
Statement only.
SIZEwrites its result to thedestinationoperand instead of returning a value, soWrk_Count := SIZE(Samples, 0);is an error. Call it on its own line, then use the destination tag. -
The whole array, or its first element.
SIZE(Samples, 0, Wrk_Count)andSIZE(Samples[0], 0, Wrk_Count)mean the same thing. Any other element is an error, because there is no such thing as the size of a run starting part-way along:SIZE array argument must be the array itself or its first element, such as 'Samples' or 'Samples[0]' -
Scalar tags are rejected. Pointing
SIZEat a non-array tag produces:SIZE array needs an array tag, but 'Count' holds one value -
Dimension is always the literal
0. A tag or any other number produces:SIZE dimension argument must be the literal 0 -
Destination must be
DINT— a scalar tag or a single array element, not a whole array. The Ladder form takes aREALdestination as well; this one does not.
In Ladder
SIZE is on the Array tab in Ladder too, with the same three operands. See
SIZE in Ladder.
COP and CPS — Copy
COP and CPS are the Structured Text instructions in rungs.dev that copy a run of elements from one array into another, clamped to whichever array runs out first.
SRT — Sort
SRT is the Structured Text instruction in rungs.dev that sorts a run of array elements into ascending order in place, using the length and position on its CONTROL tag.