Modifying object variables in Javascript

Hello I’m trying to have a function change a value through the State.setVar command in Javascript, but not having any luck. It runs, but the variable remains unchanged. Is it possible to do this by passing a captured temp variable? I’m guessing not as it might be just a copy of the actual variable? Thanks

<<print setup.reduceUses($Playerinventory[_i].uses)>> 

JS function

setup.reduceUses = function(varcurruses){
	State.setVar(varcurruses, varcurruses - 1);	
	return varcurruses;
}

If you are requesting technical assistance with Twine, please specify:
Twine Version:
Story Format: Sugarcube 2.314

According to the SugarCube docs, I think you might be missing the sigil on varcurruses? In the example from the docs, the sigil is $. Can you console.log(varcurruses) to see if the variable contains a sigil?

Docs: SugarCube v2 Documentation

Disclaimer: I have no idea what I’m talking about because I’ve never developed with Twine. But hopefully, this helps to nudge you back on track.

No you don’t use the $ in javascript, only in twine. Thanks anyways.

Not sure why you’re doing something via a function that you can do directly, but….

That’s not how State.setVar() works.

 

To keep with what you’ve already attempted, you’ll need to do something like the following:

<<print setup.reduceUses("$Playerinventory[_i].uses")>>
setup.reduceUses = function (varCurUses) {
	var newUses = State.getVar(varCurUses) - 1;
	State.setVar(varCurUses, newUses);
	return newUses;
};

 

That said, and as long as you’re using objects, it would be more straightforward to pass the object reference in and access its uses property directly. For example:

<<print setup.reduceUses($Playerinventory[_i])>>
setup.reduceUses = function (invItem) {
	invItem.uses -= 1;
	return invItem.uses;
};
1 Like

Thanks for clarifying. I did have one question on one line of your code. What would be the difference between:

var newUses = State.getVar(varCurUses) - 1;

and

var newUses =  varCurUses - 1;

The former resolves the variable expression you passed in as a string into its actual value, via State.getVar(), then subtracts 1 from it.

The latter attempts to subtract 1 from the string you passed in.