-
2
- #1
Ran into this strange bug today. Seems to be a lesson in how VFP scoping can be weird, and why you should always initialize variables. Code is below.
Output, annotated:
Essentially, though I hide pcVar from TestProc() with PRIVATE, TEXT TO pcVar sets the hidden, out of scope pcVar instead of creating a new private variable scoped within TestProc(). Interestingly, if there are multiple hidden variables at the same time, TEXT TO will set the closest variable in the callstack.
This isn't specific to out-of-scope PRIVATE variables: TEXT..ENDTEXT will also update out-of-scope PUBLIC variables.
This wouldn't be an issue if I had instantiated pcVar within TestProc() between the PRIVATE and TEXT TO command, which serves as a lesson to always instantiate your variables.
Code:
CLEAR
*
* [1] Initialize pcVar, which is PRIVATE by default
*
pcVar = PROGRAM()
DISPLAY MEMORY LIKE pcVar
TestProc()
*
* [5] pcVar updated to 'TESTPROC'
*
DISPLAY MEMORY LIKE pcVar
RETURN
******************
PROCEDURE TestProc
******************
*
* [2] Hide pcVar from this procedure
*
PRIVATE pcVar
DISPLAY MEMORY LIKE pcVar
*
* [3] Write to pcVar, which *should* be a new variable, private *to this procedure* by default
*
TEXT TO pcVar NOSHOW TEXTMERGE
<<PROGRAM()>>
ENDTEXT
*
* [4] TEXT...ENDTEXT just updated a hidden variable
* Note: if pcVar were PUBLIC in the calling procedure, it would still get updated
*
* Initializing pcVar after the PRIVATE command, but before the TEXT...ENDTEXT block would completely avoid this error
*
DISPLAY MEMORY LIKE pcVar
RETURN
ENDPROC
*******
Output, annotated:
Code:
[1] PCVAR Priv C "00002Q6H01J7" 00002q6h01j7
[2] PCVAR (hid) C "00002Q6H01J7" 00002q6h01j7
[4] PCVAR (hid) C " TESTPROC" 00002q6h01j7
[5] PCVAR Priv C " TESTPROC" 00002q6h01j7
Essentially, though I hide pcVar from TestProc() with PRIVATE, TEXT TO pcVar sets the hidden, out of scope pcVar instead of creating a new private variable scoped within TestProc(). Interestingly, if there are multiple hidden variables at the same time, TEXT TO will set the closest variable in the callstack.
This isn't specific to out-of-scope PRIVATE variables: TEXT..ENDTEXT will also update out-of-scope PUBLIC variables.
This wouldn't be an issue if I had instantiated pcVar within TestProc() between the PRIVATE and TEXT TO command, which serves as a lesson to always instantiate your variables.