Variable is not an array when in a for loop


#1

I try to make myself a reusable and scalable attribute switcher. The idea is to have a list of attributes stored in a list, and for each of them trigger the attribute.

I do have a working base for one unique attribute:

string $myAttr = "myObject1.holdOut";
setAttr $myAttr (!`getAttr $myAttr`);

But I struggle when I want to have the scalable version using an array and a for loop:

string $myAttr[] = {"myObject1.holdOut", "myObject2.holdOut"};
for ($i = 0; $i < `size $myAttr`; $i++){
    print ($myAttr[$i] + "\n");
    setAttr $myAttr[$i] (!`getAttr $myAttr[$i]`);
    }

It retrurns line 4.47 "$myAttr" is not an array

What do I have wrong ?


#2

Oh well, someone gave me the answer : I used the variable somewhere else during the same Maya session, so either I change the variable name or I reboot Maya.

Here’s the completed script if you are interested:

// ***************************************************
//                       README
// ***************************************************
// ***************************************************
// As the examples show, put your arrtribute IDs in 
// the list after line 16 between quotation marks like
// these: "" and with a coma , at the end. EXCEPT for 
// the very last element of the list.
// If you don't know your attribute id, open your 
// script editor, clear the top-part history, and 
// toggle the attribute manually. The script history 
// should show something like :
//        setAtt "yourObject.attribute"
// Copy what's between the quotes.

string $attrList[] = {
    "myObject.holdOut",
    "myOtherObject.holdOut"
};
for ($i = 0; $i < `size $myAttr`; $i++){
    setAttr $attrList[$i] (!`getAttr $attrList[$i]`);
}

// Written by Loïc "L0Lock" DAUTRY
// Source:
// https://gist.github.com/L0Lock/c1330ee50b0775b23b34ec969f73906e

#3

One thing that people don’t think much about is what happens if you are writing some quick scripts in the Script Editor. In that case, you can easily end up declaring a global variable, even if you didn’t explicitly declare it global, and that’s when you hit this kind of problem.

What I normally do when I’m writing things in the Script Editor is to always wrap my code in { }'s. That way your variables stay local and don’t mess up any other scripts.