static <block of static vars with initial values><function>
3. Example
Declares a counter:
count: static [n: 0] does [n: n + 1]
Uses the counter in the console:
> count
== 1
> count
== 2
...
As a side effect, funcs can be referenced by 'self :
fact: static [] func [n][either n < 2 [1][n * self n - 1]]
4. Commented Code
static: func [
"Builds a function with static vars"
vars [block!] "Block of set-words value pairs"
func [function!] "Function"
][
; builds an object ('vars) containing the vars
vars: context vars
; binds the body of the function to the 'vars object
bind second :func in vars 'self
; attaches the function to the 'vars object
vars/self: :func
]
5. REBOL 3 Considerations
'static doesn't works in r3 anymore, as functions' bodies are no longer accessible. It isn't a problem, as closures allows to build similar functions.
A counter declaration:
count: do closure [n] [does [n: n + 1]] 0
A Factorial function:
fact: do closure [/local self] [
self: func [n] [
either n < 2 [1] [n * self n - 1]
]
]