Notifications
Clear all

[Closed] how to use the "collect "command?

Is there a help page that describes exactly how to use the “collect “command?
searching max script help seems to yield the usual “related to, but not exactly <command>” pages.

33 Replies

I believe it’s under “For loop” in the max script help

The collect <expr> form gathers the expression values from the loop iterations and stores them in an array, which is then yielded as the value of the overall for loop. This, for example, is a good way to gather procedural selections of objects from a scene. If the where expression is used with the collect form of the for loop, only the values from those iterations for which the where expression is true are collected. This can be used to collect a filtered sub-set of the iterated values. You can also achieve this collection filtering in a for loop that does not use a where expression by yielding the special value dontCollect for those iterations that should not be added to the collection.

on the very base level, collect allows you to directly create an array rather than declaring one first, and appending the values.

i.e:
arr = #()
for i in (selection as array) do append arr i

vs:
arr = for i in (selection as array) collect i

it does allow you to do nice filter operations in one hit too, like finding objects of a certain name –

arr = for i in (selection as array) where (matchpattern i.name pattern:"woop*") collect i 

thanks for your responses.

I believe it’s under “For loop” in the max script help

Of course ! How silly of me to think I could look up a keyword by the keyword.

And don’t forget about dontCollect

can anyone give an example of why you should use dontcollect over where?

And by that I don’t mean how do you use the syntax, I get it – I’m just not seeing how it is useful.

1 Reply
(@denist)
Joined: 11 months ago

Posts: 0

if a condition is long by code for easier reading is better to use dontcollect:


for node in nodes where isvalidnode node and node.ishidden do
(
	if node.baseobject.custattributes[#keymonitorAttribute] == undefined then dontcollect else node
)

 JHN

I use it when I have an elaborate check in the the for loop. The where clause is what I mostly use, but when I do lots of checks I’d do it in the if loop for readability sake. Also look into continue it will just skip that to the next iteration.

-Johan

1 Reply
(@denist)
Joined: 11 months ago

Posts: 0

the using of continue makes the loop much, much slower

 JHN

I know you’re a speed freak Denis
But when I have a loop of 10 to max 100 iterations of not heavy checks, I don’t care too much about speed and more about readability and code reuse.

But good to know! I don’t use break, exit and return, see I do care a bit

sometimes you can’t know how many iterations a loop can have

 JHN

True, and then there’s autism and OCD

Just kidding though, learning a lot of good practices reading your posts!

Cheers,
-Johan

Page 1 / 3