is it possible to have static variable inside a re

2019-06-05 19:22发布

问题:

This shows how to have a static variable inside an object or context: http://www.mail-archive.com/list@rebol.com/msg04764.html

But the scope is too large for some needs, is it possible to have a static variable inside an object function ?

回答1:

In Rebol 3, use a closure (or CLOS) rather than a function (or FUNC).

In Rebol 2, fake it by having a block that contains your static values, eg :

f: func [
   /local sb
][
     ;; define and initialise the static block
 sb: [] if 0 = length? sb [append sb 0]

     ;; demonstate its value persists across calls
 sb/1: sb/1 + 1
 print sb
 ]

    ;; sample code to demonstrate function
 loop 5 [f]
 == 1
 == 2
 == 3
 == 4
 == 5


回答2:

Or you can use FUNCTION/WITH. This makes the function generator take a third parameter, which defines a persistent object that is used as the "self":

accumulate: function/with [value /reset] [
    accumulator: either reset [
        value
    ] [
        accumulator + value
    ]
] [
    accumulator: 0
]

To use it:

>> accumulate 10
== 10

>> accumulate 20
== 30

>> accumulate/reset 0
== 0

>> accumulate 3
== 3

>> accumulate 4
== 7

You may also want to look at my FUNCS function.



标签: rebol