Using lists in CoBlocks

Lists in CoBlocks

Lists are a kind of variable that store multiple values. With the help of lists you can perform actions for several items at once, keep track of a shopping lists, calculate the sum of several numbers, and more!

1. My first list

Similar to making variables, lists are created with a statement block. You can find the create empty list - block in the Data -> Lists category.

All lists start empty. Let’s add items to ours!
In our scene we prepared 5 (dog-) items we’ll add with the add item to list - block.

2. Using the list

Now that all our dogs are in our list, let’s have them race for the finish line!
An easy way to use an action on all items in a list is the for each - block. Here is how it’s used:

  1. In the Control -> Loops category, drag the for each - block into your workspace.
    This block creates a variable called “element” which represents every item in your list. You can find it in Data -> Variables category.
  2. Place a move item - block inside of the forEach - loop.
  3. Place the element - variable into the move item - block.

Now, we’ll perform an action for every dog in our list! Let’s see the code in action.

Click to see the code in action

…huh? The dogs are running after each other, but not at the same time!

In CoBlocks, blocks that perform an action over time will stop our code until the action is done. The first dog runs first, then the second, then the third, then the fourth, … the behaviour in our example is correct from a code perspective, but it is not the outcome we want.

3. Perform actions for all list items at the same time

Keep in mind that some blocks may take a while to complete before other blocks can run. To help out with situations like that we have the run separately - block. You can find it in the Control -> Other category.

The run separately - block will run all code you place into it, while telling CoBlocks to continue to the next block. This is a very handy helper for performing actions on lists, but also for functions.

Click to see the new example in action

4. Wrapping up

Lists are a powerful tool to help you make compact CoBlocks code. This introduction lesson scratches only the surface of what you can do with lists.

More in-depth tutorials about using lists will follow! Keep an eye out on updates in this forum :slight_smile: