Grasshopper Scripting 104
Grasshopper Scripting 104
Lists
In the last post we discussed applying conditional operations to single
values. But that is way too simple. We expect to process many different
values when working with Grasshopper and the power of scripting increases
when we deal with collections of data. The main collection type you should
care about is The List.
In order to process a list we are going to need a bit more of flow control than
just conditionals but before diving into loops let’s see how to declare and
populate a list inside a C# component.
Lists are a special construct that needs to be declared with a sentence you
should get familiar to.
We must precede our variable name with the words “List<dataType>” and
then assign a “new” empty list by calling the function “List<double>()”.
Whenever you see a statement with empty parenthesis like .ToString() you
are dealing with a function (called methods in C# jargon).
In the second lesson we talked about reference-type values saying they were
more flexible. You have to be careful when dealing with them as they behave
quite different from value-type variables. Let’s seen an example.
The result here is something we would expect, the second variable gets the
same as the first, then we alter the former but the later stays the same.
Now let’s do something similar with a list of strings:
That’s why, on the previous example, we created the copy of the list not
using a “=” statement but a speciall method of Lists:
Understanding this is important not to get fooled when working with loops
and complex assignments.
Challenge
1. Write a component that checks if a list has an odd number of items and if
so, returns the element at the middle.
2. Write your own version of the List Item component.