Skip to content

Instantly share code, notes, and snippets.

@honix
Last active September 5, 2017 15:24
Show Gist options
  • Save honix/2c72e78bdc4b2d6511283d0436688744 to your computer and use it in GitHub Desktop.
Save honix/2c72e78bdc4b2d6511283d0436688744 to your computer and use it in GitHub Desktop.
Red []
let: func [
binds
block
/local
ctx
][
ctx: context append/only append binds copy [result: do] block
select ctx 'result
]
g: 1
b: 42
let [
a: 100
b: 200
c: b - a
][
a + b + c + g
] ;-- will return 401
b ;-- will return 42 from global context
let [a: 1 b: 2 c: 3] [let [g: 15] [a + b + c + g]] ;-- will return 21
@draegtun
Copy link

Have a look at the WRAP function which was added to Rebol 3 - metaeducation/rebol-issues#2119

wrap [
    a: 100
    b: 200
    c: b - a
    a + b + c + g
]

It's very easy to implement:

>> source wrap
wrap: make function! [[
    {Evaluates a block, wrapping all set-words as locals.}
    body [block!] "Block to evaluate"
][
    do bind/copy/set body make object! 0
]]

However unfortunately the BIND/SET refinement isn't implemented in Red just yet :(

@9214
Copy link

9214 commented Aug 23, 2017

let: func [spec src][do bind src context spec]

And regarding wrap, here's the trick:

>> g: 1
>> context [a: 100 b: 200 c: b - a return a + b + c + g]
== 401

@draegtun
Copy link

draegtun commented Sep 5, 2017

In Rebol 3 (Ren-C):

>> g: 1
== 1

>> wrap [a: 100 b: 200 c: b - a   a + b + c + g]             
== 401

>> context [a: 100 b: 200 c: b - a  a + b + c + g]       
== make object! [
    [self: a b c]
    [
        a: 100
        b: 200
        c: 100
    ]
]

>> context [a: 100 b: 200 c: b - a return a + b + c + g]
** Script Error: RETURN called with no generator providing it in use
** Where: return construct context
** Near: c + g ??
** File: ../src/core/n-function.c
** Line: 215
ⓘ  Note: use WHY for more error information

CONTEXT should always return an OBJECT! :) Hence why WRAP was added to Rebol 3 (and Ren/C branch went further and disallowed RETURN).

@honix
Copy link
Author

honix commented Sep 5, 2017

Updated/clarified 'let

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment