Invalid use of the THIS keyword
The THIS keyword provides access to the current instance of a FUNCTION_BLOCK. However, there are several rules governing its proper use:
Common errors
-
Using
THISoutside of aFUNCTION_BLOCKcontext: TheTHISkeyword can only be used inside aFUNCTION_BLOCKor itsMETHODs orACTIONs. It cannot be used inFUNCTIONs,PROGRAMs, or . -
Not dereferencing
THISto access members: When accessing members usingTHIS, it must be dereferenced using the^operator:THIS^.member. -
Member access position:
THIScannot be accessed as a member of another object. Expressions likex.THIS^are invalid. -
Global access position:
THIScannot be used with the global access operator (.THIS^.member). -
Using
THISwith type cast operators: The type cast operator (<type>#) cannot be used withTHIS.
Examples of invalid use
// Error: Using THIS outside `FUNCTION_BLOCK` context
FUNCTION func
THIS^.x := 2; // Error: Invalid use of `THIS`
END_FUNCTION
// Error: Not dereferencing THIS when accessing members
FUNCTION_BLOCK fb
THIS.x := 20; // Error: `THIS` must be dereferenced to access its members
END_FUNCTION_BLOCK
// Error: THIS in member access position
FUNCTION_BLOCK fb
x.THIS^.y := 20; // Error: `THIS` is not allowed in member-access position
END_FUNCTION_BLOCK
// Error: Global access position
FUNCTION_BLOCK fb
.THIS^.x := 20; // Error: `THIS` is not allowed in global-access position
END_FUNCTION_BLOCK
// Error: Using THIS with type cast
FUNCTION_BLOCK fb
p := fb#THIS; // Error: The `<type>#` operator cannot be used with `THIS`
END_FUNCTION_BLOCK
Examples of valid use
FUNCTION_BLOCK Counter
VAR
count : INT;
enabled : BOOL;
END_VAR
// Valid: Direct use in FUNCTION_BLOCK implementation
METHOD increment
IF THIS^.enabled THEN
THIS^.count := THIS^.count + 1;
END_IF
END_METHOD
// Valid: Using THIS to pass the instance to another FB
METHOD send_to_logger : BOOL
VAR_IN_OUT
logger : Logger;
END_VAR
logger.log_counter(THIS);
END_METHOD
// Valid: Using THIS to compare with another instance
METHOD equals : BOOL
VAR_IN_OUT
other : Counter;
END_VAR
equals := THIS^.count = other.count;
END_METHOD
ACTION my_action
IF THIS^.enabled THEN
THIS^.count := THIS^.count + 1;
END_IF
END_ACTION
END_FUNCTION_BLOCK