Pages

Friday, December 18, 2009

Include/Exclude in FOR loops via WHERE

Here I'll focus on a specific MAXScript usage. It's about WHERE which looks like IF but can be used only in FOR loops and its very handy to filter out items from collections (for example - to exlude objects from selection).

SOME EXAMPLES:

-- collect objects which has "height" property
objs = for o in objects where \
hasProperty o "height" collect o

-- collect Multimaterials from scene
MMats = for m in sceneMaterials where \
classOf m == Multimaterial collect m

-- filter array and collect integer values to a new array
oldArray = #("a", 12, "b", 3.5, 7)
newArray = for i in oldArray where \
classOf i == integer collect i

--> #(12, 7)


Using WHERE in FOR loop is not something hard, its a logic play only, we just need to choose correct expression check suitable for your concrete case.

Into MAXScript Reference search for "TargetObject" and you'll find a good examples for how to filter the TargetObject out using "where".

FOR EXAMPLE:

-- old and bad style coding (SLOW):
for o in Lights do
try(o.rgb = random black white)catch()
-- Optimized code:
for o in Lights where classOf o != TargetObject do
o.rgb = random black white

So, shortly to say, we can filter our collection checking its items by class, categories or property, and this can be done tidiness and faster using WHERE.

MORE EXAMPLES (forum topics):
Basic script example
How to filter out shapes only in selection.

Collecting Photometric lights
Collect in array all photometric lights that are selected.

Remove specific type of object from scene
Delete all PF_Source in the scene.

Select objects with 0 vertices
How to exclude (delete or deselect) objects with 0 vertices (helpers objects).

2 comments:

  1. This is a great post. Advanced/updated coding techniques are missing from current training aids for beginning MAXscript.

    ReplyDelete

Thanks for your comment