ZBrushCentral

Loop in reverse

How do you loop in reverse decrement?
And (hitting two birds with one stone) get the length of an array in Zscript?

The JavaScript equivalent of:

s = "12345"; o = "" for (var i = s.length - 1; i >= 0; i--) { o+= s; }

>> “54321”

[IButton,DoIt,
[VarSet,newStr,""]
[VarSet,whatsit,“12345”]
[VarSet,index,[StrLength,#whatsit]-1]
[Loop,[StrLength,#whatsit],

[VarSet,newStr,[StrMerge,newStr,[StrExtract,#whatsit,index,index]]]

[VarDec,index]

]
[VarSet,whatsit,newStr]
[Note,whatsit]
]

Thanks for that, Marcus!

I forgot the other part - which is to loop over an array backwards appending data to a new array. I looked in the docs for arr.length (or equivalent) but could only find StrLength

Here’s that loop in JavaScript:

var arrA = [1, 2, 3, 4, 5];
var arrB = [];

for (var i = arrA.length - 1; i >= 0; i–)
{
temp = arr
arrB.push(temp);
}

>> arrB = [5,4,3,2,1]

In zscript you’d use a list variable. You have to define its size when it’s declared:

[VarDef,myList(10),""] // a list of ten strings

[VarDef,myList(10),0] // a list of ten floats

Then all you’d need to do is decrement the index inside the loop in the same way as above.

Question: Can you have two variables (float & a string) called the same thing at the same time?
I take it you then update the array count as you modify the array?

No, you can’t have two variables with the same name. But that shouldn’t matter, depending on what you’re trying to do.

You can’t change the length of a list variable dynamically, so you’d have to create it large enough for whatever you might want to put into it. You could then increment a second variable every time you added a value, so you’d know how many you’d got.

Rather than trying to directly convert javascript to zscript you’d do well to get a bit more familiar with zscript. The two languages differ quite a lot. The ZScript Command Reference gives a breakdown of what’s available.

HTH,

Thanks for the help. Believe me I’ve looked over the documentation. And yes, when learning a new programming language it’s easy to fall back on another language of what you know when trying to bridge a gap of the “unknown”.

I just want to grasp a few (basic) building blocks of code - such as a for next loop in reverse, reading & writing to a file, iterating over an array, appending an array, turning a string into an int etc, before venturing out into the wild world of ZScripting.