How is the RETAIN keyword considered for function block instances?

Concerning RETAIN and NON_RETAIN, the â†’variables of â†’function block instances are treated as the section VAR in which the function block instance has been declared. This means:

  • If the keyword RETAIN is defined in section VAR, the variables of the function block instance are treated as they would have been declared with RETAIN.

  • If the keyword NON_RETAIN is defined in section VAR, the variables of the function block instance are treated as they would have been declared with NON_RETAIN.

The following cases are treated as exceptions:

  • One or more variables are explicitly declared as NON_RETAIN or RETAIN in the declaration of the appertaining function block.

  • If function block instances are declared again in the declaration of the appertaining function block, RETAIN or NON_RETAIN declared in the section VAR of the first function block instance is not valid for their variables (but the one in the appertaining function block).

Here an example how the above rules are applied:

Copy

ST-code that is the basis for the following table

PROGRAM Test
  VAR RETAIN
    myFB1 : FB1;
    var1  : INT;
  END_VAR
END_PROGRAM
  
FUNCTION_BLOCK FB1
  VAR
    var2  : INT;
    myFB2 : FB2;
    myFB3 : FB3;
  END_VAR
  VAR NON_RETAIN
    var3    : INT;
    myFB3_2 : FB3;
  END_VAR
  VAR RETAIN
    var7    : INT;
    myFB3_3 : FB3;
  END_VAR
END_FUNCTION_BLOCK
  
FUNCTION_BLOCK FB2
  VAR
    var4  : INT;
  END_VAR
  VAR NON_RETAIN
    var5  : INT;
    myFB3 : FB3;
  END_VAR
END_FUNCTION_BLOCK
  
FUNCTION_BLOCK FB3
  VAR
    var6  : INT;
  END_VAR
END_FUNCTION_BLOCK

The variable...

is treated as ...

Reason

Test.var1

RETAIN

keyword RETAIN in line 2

Test.myFB1.var2

RETAIN

keyword RETAIN in line 2 (because there is no keyword in line 9)

Test.myFB1.var3

NON_RETAIN

keyword NON_RETAIN in line 14

Test.myFB1.var7

RETAIN

keyword RETAIN in line 18

Test.myFB1.myFB2.var4

NON_RETAIN

no keyword in lines 9 and 25
(The keyword RETAIN in line 2 is not applied for this variable because FB2 is declared in FB1.)

Test.myFB1.myFB2.var5

NON_RETAIN

keyword NON_RETAIN in line 28

Test.myFB1.myFB3.var6

NON_RETAIN

no keyword in lines 9 and 35
(The keyword RETAIN in line 2 is not applied for this variable because FB2 is declared in FB1.)

Test.myFB1.myFB3_2.var6

NON_RETAIN

keyword NON_RETAIN in line 14 (because there is no keyword in line 35)

Test.myFB1.myFB3_3.var6

RETAIN

keyword RETAIN in line 18 (because there is no keyword in line 35)

Test.myFB1.myFB2.myFB3.var6

NON_RETAIN

keyword NON_RETAIN in line 28 (because there is no keyword in line 35)