Script Executed after Error

Find out why the . goes before the /

Moderator: Paul Tuersley

Post Reply
Klustre
Posts: 21
Joined: July 27th, 2011, 2:53 am

Hi everyone!

I've been learning to script for the last two weeks or so and man, is it addictive :)
Though, something is unclear. The code below returns 'undefined is not an object' on the second line of the loop. The Intro to Scripting PDF tells me this error is only returned when the hierarchy isn't completly defined. But the hierarchy is well defined in this case. Or am I missing something? The weird thing is that the script is executed anyway after I cancel from ExtendScript Toolkit.

As far as I know the square brackets are right, since selectedLayers returns an array. And if I use a break on the third line of the loop, there is no error, but the loop obviously breaks after the first layer.

Could anyone enlighten me?

Code: Select all

var myComp = app.project.activeItem;
var myLayers = myComp.selectedLayers;
var myDuration = myComp.workAreaDuration;

for(var i = 0; i <= myLayers.length; i++){
        //myLayers[i].inPoint = myComp.workAreaStart;
        myLayers[i].outPoint = myDuration;//hm, returns 'undefined is not an object', but performs action after cancel.
        }
Paul Tuersley
Posts: 704
Joined: June 5th, 2004, 7:59 am
Location: London, UK

It's because you have:

Code: Select all

for(var i = 0; i <= myLayers.length; i++){
when it should be:

Code: Select all

for(var i = 0; i < myLayers.length; i++){
Currently, if myLayers.length was 1, it would loop twice, once for 0, then for 1. But there is no myLayers[1] object, so it fails on the second loop.

Generally, if you're looping through the index of an array, which starts from 0, you'll just use " < ". Exceptions to this are things which store items starting with an index of 1, which are typically things like myComp.layer(i) which refer directly to the layer index (i.e. layer numbers start from 1)

So, example of loop starting at 0:

Code: Select all

for(var i = 0; i < myLayers.length; i++){
	myLayers[i].outPoint = myDuration;
}
And another starting at 1:

Code: Select all

for(var i = 1; i <= myComp.numLayers; i++){
	myComp.layer(i).outPoint = myDuration;
}
Klustre
Posts: 21
Joined: July 27th, 2011, 2:53 am

Perfect, thank you Paul.
Post Reply