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

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.