开发者

is it possible to have static variable inside a rebol function?

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开发者_JAVA技巧 scope is too large for some needs, is it possible to have a static variable inside an object function ?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜