Page 1 of 1
Pass initial value for a persistent variable to function.
Posted: Sat Jun 15, 2024 4:27 pm
by Psychophanta
As we know, we can initialize a persistent local variable 'Static' with a constant value.
Is there a way or trick to pass an initial value to one of the 'Static' variables to a function?
Re: Pass initial value for a persistent variable to function.
Posted: Sat Jun 15, 2024 4:48 pm
by mk-soft
Only with query of the static variable.
What do you want to achieve?
Code: Select all
Procedure foo(value, init = 1)
Static count
Protected r1
If Not count
count = init
EndIf
r1 = count
count + 1
ProcedureReturn r1
EndProcedure
Debug foo(0, 10)
Debug foo(0, 10)
Debug foo(0, 10)
Debug foo(0, 10)
Debug foo(0, 10)
Debug foo(0, 10)
Debug foo(0, 10)
Debug foo(0, 10)
Re: Pass initial value for a persistent variable to function.
Posted: Sat Jun 15, 2024 5:02 pm
by mk-soft
It is better to outsource the static variable and pass it as a ByRef. This allows the function to be used multiple times.
Code: Select all
Procedure foo(value, *position.integer)
Protected r1
*position\i + value
r1 = *position\i
ProcedureReturn r1
EndProcedure
Define pos = 10
Define pos2 = 100
Debug foo(1, @pos)
Debug foo(10, @pos2)
Debug foo(1, @pos)
Debug foo(1, @pos)
Debug foo(10, @pos2)
Debug foo(10, @pos2)
Debug foo(10, @pos2)
Debug foo(0, @pos)
Re: Pass initial value for a persistent variable to function.
Posted: Sat Jun 15, 2024 6:00 pm
by Psychophanta
Is a solution, even the variables are out of the function and things are not so organized, and you are forced to reserve variables outside for its use just inside, the variables are available for is use (read/write) outside, etc., but as workaround in a hurry could be useful.
To explain it better i would teach it like this:
Code: Select all
Procedure foo(value, *position.integer)
*position\i + value
EndProcedure
pos = 10
pos2 = 100
foo(1, @pos):Debug pos
foo(10, @pos2):Debug pos2
foo(1, @pos):Debug pos
foo(1, @pos):Debug pos
foo(10, @pos2):Debug pos2
foo(10, @pos2):Debug pos2
foo(10, @pos2):Debug pos2
foo(0, @pos):Debug pos