0

I'm trying to create a macro that expands an incrementing value into the output every time it is called. So far I've got this, but it re-initializes the value to 0 every time:

macro test1 {
    case { _ $x
    } => {
        var n = n ? n+1 : 0;
        letstx $n = [makeValue(n,#{here})];
        return #{
            $n;
        }
    }
}

test1 ()
test1 ()

yields:

0;
0;

when what I want is:

0;
1;

How do I define n to be a global variable, so that I can increment and retain its value outside the macro?

Update:

I can get it to work by changing the assignment to n to an eval, but this really feels like cheating:

var n = eval("if (typeof n != 'undefined') n++; else n=0; n")
Michael
  • 9,060
  • 14
  • 61
  • 123
  • What you want to achieve is not what Sweet.js comes for in MHO. Actually, you don't really need Sweet.js in this case. It can be achieved with pure JS as stated in the thread [here](http://stackoverflow.com/questions/1535631/static-variables-in-javascript). – Season Oct 20 '15 at 02:30
  • If you have access to a global object such as "window" then you can utilize that, by adding a property such as "n" to the window object. – Don Oct 20 '15 at 02:51
  • @Season This is just a simplified test case, actually. I really do need sweet.js for its macro expansion. – Michael Oct 20 '15 at 04:29

1 Answers1

1

At the moment (there are plans make this better) you can just use the global object:

macro test1 {
    case { _ $x
    } => {
        window.n = typeof window.n !== 'undefined' ? window.n+1 : 0;
        letstx $n = [makeValue(n,#{here})];
        return #{
            $n;
        }
    }
}

test1 ()
test1 ()
timdisney
  • 5,287
  • 9
  • 35
  • 31
  • I don't think using `window` is portable... but I just tried a quick experiment and it appears I can just use "n" by itself (without defining it as a var) and it will show up in the global environment. – Michael Oct 20 '15 at 17:10
  • 1
    True. If you want to be explicit I think `this.p` should work everywhere. – timdisney Oct 20 '15 at 20:36