in one of my last posts I discussed the usage of the VAR declarations: VAR_TEMP, VAR_STAT and VAR CONSTANT. I don’t know what happened, but somehow I completely missed the existence of the variable declaration VAR_INST. I only learned about it a few weeks ago. So in case more people missed this VAR declaration I created this post about VAR_INST.
What is it?
Instance variables are available for function block methods and unlike ‘normal’ variables an instance variable is saved on the stack of its parent function block. Instance variables can be declared like other variables:
VAR_INST Variable : Type; END_VAR
Saved on the stack of its parent? Yes, that does mean that the variable is placed ‘on’ the function block rather than on the method which it declared. The variable’s value will thus be persistent as long as the function block is alive.
Time for an example:
Consider the following function block ‘CycleInformation’
FUNCTION_BLOCK PUBLIC CycleInformation
This function block has a method: ‘CycleInformation’.
METHOD PUBLIC MoreThan10Cycles : BOOL VAR_INST _count : INT; END_VAR
_count := _count + 1; IF _count › 10 THEN MoreThan10Cycles := TRUE; ELSE MoreThan10Cycles := FALSE; END_IF
Of course you noticed the VAR_INST declaration: _count. Any ‘normal’ variable will be reinitialized on each method call, however not this instance variable.
When we use this function block in a program:
PROGRAM MAIN VAR _cycleInformation : CycleInformation; END_VAR
IF _cycleInformation.MoreThan10Cycles() THEN ; END_IF
and run this program with a break point:
Notice that the instance variable is saved between the method calls which results in an increasing value.
When to use it?
Okay, nice, but when do you use it? good question. As far as I’m aware instance variables do not bring you new features. The counter variable the above example could simply be declared directly in the function block. However, it can help you in maintaining your code. If a variable does not need to be declared as global variable you don’t do it. If a variable does not need to be declared in the function block, you don’t do it. Keep your variables scopes as small as possible! This helps you dependencies and responsibilities small.
Conclusion
In this post I describe the instance variables, declared with VAR_INST. Instance variables are available for function block methods. Instance variables are saved on their containing function block and there values are thus preserved between calls.