Script Library: 1213 scripts
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 
View scriptLicenseDownload documentation as: HTML or editable
Download scriptHistoryOther scripts by: vincentecuye

Documentation for: static.r


REBOL

static.r

Author: Vincent Ecuyer
Date: 30-Jan-2013

Contents:

1. Purpose
2. Usage
3. Example
4. Commented Code
5. REBOL 3 Considerations

1. Purpose

Functions with static vars

2. Usage

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]
    ]
]
MakeDoc2 by REBOL- 30-Jan-2013