Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Custom macros: Adding parameter value to existing macro value

I have a custom macro, which I want to be able to add a numerical value to an existing variable.  However, I want to be able to possibly set other variables at the same time.  So, for example, it might look like this:

<<question var1 10 var2 5 var3 "boo">>

What this would do is add 10 to var1, add 5 to var2 and set var3 to "boo". 

I currently have this custom macro code:
macros.question2 = {
handler: function(place, macroName, params, parser) {
var left, right;
for (var index = 0; index < params.length; index += 2) {
var s;
if (isNaN(params[index+1])) {

var currentgoo2 = "state.history[0].variables." + params[index];
var add2goo = params[index+1];
var newgoo2 = currentgoo2 + + add2goo;

// foo = state.history[0].variables.goo2 + + (params[index+1]);

----This line above works if I substitute newgoo2 for foo, but I don't want a hard - coded variable in here.

s = "state.history[0].variables." + params[index] + " = " + newgoo2;
} else {
s = "state.history[0].variables." + params[index] + " = " + params[index+1];
}
eval(s);
}
},
};
But for some reason, it just returns a value of 5 when adding the parameter value to the variable total and I don't understand why, because if I call currentgoo2 and add2go separately, they return correctly as 9 and 5.  I know if I hard code in the name of the variable I wish to change, I can get it to add the parameter to the total value (the working line is commented out in the above example), but as soon as I try to substitute the variable name for what is included in the parameter, it just doesn't work (or returns 5 which is wrong).  Obviously I'm missing something, but I can't figure it out, any ideas?

I've attached examples below, specifically it is the question2 macro I'm having an issue with.  The else seems a bit borked, but I guess I've messed something in the initial if, although I'm struggling to see what.  I'm running this in Sugarcane, Twine 1.4.1. 

TWS Example | HTML Example

Comments

  • As long as you're using simple $variables, something like this should suffice:

    macros.question2 =
    {
    handler: function (place, macroName, params, parser)
    {
    for (var i = 0; i < params.length; i += 2)
    {
    if (isNaN(params[i+1]))
    {
    state.history[0].variables[params[i]] = params[i+1];
    }
    else
    {
    state.history[0].variables[params[i]] += Number(params[i+1]);
    }
    }
    }
    };
  • Yep, that's done the trick, thanks again. 
Sign In or Register to comment.