Skip to main content
Inspiring
July 6, 2024
Question

How to Prevent Unintended Modifications to Variables in After Effects Scripting

  • July 6, 2024
  • 3 replies
  • 964 views

 

I have a variable defined as aaa= layer.property("Source Text").value;.

To avoid modifying aaaa during subsequent processing, I created another variable called bbb:

var bbb = aaa;

However, when I modify bbb as follows:

bbb.text = ccc.text;

I noticed that aaa.text gets modified as well.

How can I resolve this issue?

This topic has been closed for replies.

3 replies

Dan Ebberts
Community Expert
Community Expert
July 6, 2024

In JavaScript, when you set a variable equal to an object (or an array) the variable contains only a reference to the object, not a copy of the object itself. So in your example, you end up with two references to the same object. Change the object via either reference, and the object will change for both references.

Inspiring
July 7, 2024

thank you for the explanation,
is there any way to make a copy of an object when handling it, or can it only be a reference?
and thank you for your contribution to the animation expression. 😊
I have noticed that many animation scriptwriters have referenced your expressions.

Dan Ebberts
Community Expert
Community Expert
July 7, 2024

It's not simple, but you could do something like this that should capture the attributes that aren't read-only:

var layer = app.project.activeItem.layer(1);
var aaa = layer.property("Source Text").value;
var bbb = new TextDocument("");
for (var i in aaa){
	try{
		bbb[i] = aaa[i];
	}catch(err){
	}
}
aaa.text = "new text";
alert (bbb.text);

What is it that you're trying to do exactly? Maybe there's another way...

 

Mylenium
Legend
July 6, 2024

I think you misunderstand how this works. You cannot arbitrarily store variables persistently in expressions or the scripting engine. You can only force it to "compare" stuff on a continual basis by running things in a loop or such. So the simplest solution would be to have an if()else{} test in your code to determine the contents of a variable based on whatever criteria and then the source value remains available whenever the criteria aren't met.

 

Mylenium

Inspiring
July 6, 2024

Got it, thank you for the explanation.

Mylenium
Legend
July 6, 2024

Without the full code nobody can understand your problem. That said, if that is all you have of course the variables will all hold the same values and/ or you are mistaking the output as the variables' values. Really impossible to say without knowing what you are actually trying to do there and how you debug the whole thing.

 

Mylenium 

Inspiring
July 6, 2024

Let's put it this way, I want bbb to be a backup of aaa. I want to modify the contents of bbb without affecting aaa. I have tried other methods, such as using JSON for deep copying, but I always got errors like:

  • "text document not of Box document type"

Could you please help me with this issue?