Static Variable Inside a Function
[1/5] from: info::id-net::ch at: 2-Dec-2002 14:57
Hello,
Is there a way to have a Static Variable' C-like inside a function to count
the number of time a function is called ?
Philippe
[2/5] from: lmecir:mbox:vol:cz at: 2-Dec-2002 16:16
Hi Philippe,
> Is there a way to have a Static Variable' C-like inside a function to
count
> the number of time a function is called ?
you can use e.g. SFUN from http://www.rebolforces.com/highfun.r
-L
[3/5] from: rotenca:telvia:it at: 2-Dec-2002 19:21
Hi Philippe
> Is there a way to have a Static Variable' C-like inside a function to count
> the number of time a function is called ?
my-func: context [num: 0 self: func [][print num: num + 1]]
or
my-func: use [num][num: 0 func [][print num: num + 1]]
or
my-func: do has [num][num: 0 func[][print num: num + 1]]
---
Ciao
Romano
[4/5] from: sunandadh:aol at: 2-Dec-2002 14:40
Phillpe:
> Is there a way to have a Static Variable' C-like inside a function to
> count the number of time a function is called ?
Ladislav:
> you can use e.g. SFUN from http://www.rebolforces.com/highfun.r
It's actual at (among other places)
http://www.rebol.org/general/sfun.html
I hacked out a way of doing this a while ago -- not as generic as Ladislav's
or as Rebolish as Romano's, but it gets the job done:
my-func: func [/local s-vars] [
;; initialise static variables
s-vars: []
if 0 = length? s-vars [insert s-vars 0] ;; first entry is invocation
count
;; add one to count
s-vars/1: s-vars/1 + 1
print s-vars/1
] ;; func
;; sample run
loop 5 [my-func]
Sunanda
[5/5] from: joel:neely:fedex at: 2-Dec-2002 13:54
Hi, Philippe,
Philippe Oehler wrote:
> Is there a way to have a Static Variable' C-like inside a
> function to count the number of time a function is called ?
>
Romano beat me to the suggestion of using an object instead of a
simple function, but just for hack value, here's a function-only
variation. (I recommend the object approach, needless to say! ;-)
foo: func [arg [string!] /reset /report /local ncalls][
ncalls: [0]
if reset [return ncalls/1: 0]
if report [return ncalls/1]
ncalls/1: ncalls/1 + 1
rejoin ["call # " ncalls/1 " with " arg]
]
which behaves as
>> foo "Hello"
== "call # 1 with Hello"
>> foo "world"
== "call # 2 with world"
>> foo "goodbye"
== "call # 3 with goodbye"
>> foo/report ""
== 3
>> foo/reset ""
== [0]
>> foo "It's me again!"
== "call # 1 with It's me again!"
-jn-
--
----------------------------------------------------------------------
Joel Neely joelDOTneelyATfedexDOTcom 901-263-4446