Search code examples
plcstcodesys

Initialize Array of Custom Types in Structured Text Syntax


In my project I have a type like:

TYPE myDataStruct :
STRUCT
    A : UINT;
    B : WORD;
    C : REAL;
    D : Custom_Obj;
END_STRUCT
END_TYPE

And I need to keep an array of this type for persistent memory. I can't just use VAR RETAIN because this particular piece of memory needs to persist through a download. The controller I am using has a way to do this but in order for it to work I need to be able to set the array equal to an initial value. So if I have declared

myarray := ARRAY[0..20] OF myDataStruct;

How do I then initialize this array to a blank array? What is the equivalent of new in other languages?

I have guessed

myarray := [21(A := 0,
               B := '',
               C := 0.0,
               D := ??? )];

But that doesn't appear to be right. It could be simplified if there were only one level deep of custom structs and for this application I could do that. However, I still don't think I have the syntax right.


Solution

  • What is the equivalent of new in other languages?

    The analog of this is

    VAR
        EmptyArray  : ARRAY[0..20] OF myDataStruct;
    END_VAR
    

    If you want to pre-populate it with default values

    VAR
        EmptyArray  : ARRAY[0..20] OF myDataStruct := [
            (A := 100, B := 200, С := 0.0, D := ???),
            (A := 34, B := 45, С := 0.1, D := ???),
            ..... etc
        ];
    END_VAR
    

    For CoDeSys 2.3 delete [ and ].

    What you have to understand that EmptyArray is not a prototype of data you need but already initialized variable.