6

Is there a way to act on multiple values for a variable? For example, x may be 1, 2, or 3. If then else allows for 2 conditions. Multiple "ifs" work, but is cumbersome.

Ideally I'd like a switch statement, such as:

switch (x) {
  case 1:
    Block1;
    break;
  case 2:
    Block2;
    break;
  case 3:
    Block3;
    break;
  default:
    break;
}
2
  • 2
    Do you mean with microPython, or the LabView-derived graphical system? Either way, the keyword you seek is or. See, for instance, <youtube.com/watch?v=mFYmjKX00pk>
    – RSchulz
    Oct 24, 2021 at 4:50
  • 1
    Something like this:switch( expression ) { case value-1: Block-1; Break; case value-2: Block-2; Break; case value-n: Block-n; Break; default: Block-1; Break; } Statement-x;
    – BobDaBrick
    Oct 25, 2021 at 15:21

1 Answer 1

4

Based on the set number, I'm assuming you're using the "Robot Inventor App", and the scratch-based graphical programming language?

If that's the case, then I think you're likely to be limited to what Scratch supports, and I don't believe that includes a native switch statement.

Based on this thread on the Scratch site, you could try using the broadcast and when I receive blocks to create a switch like statement (assuming you don't need too many of them):

Simple Switch with Broadcast

Basically, you drop the variable into the broadcast message field, and then set up the receive blocks to kick in when the relevant value is seen (I don't own the set, but was able to play around with the App in "streaming" mode to see control flowing through these blocks)

I've taken this a step further, by using the join block to combine the counter variable with a text string, which would allow for more switch statements in different parts of your program:

Filtering switches for different paths

2
  • Thank for the code. 51515 blocks can do a lot, but obvious limitations. When I was programming in Objective C for the iPhone using xcode I used the case statement when there were more than 2 choices.
    – BobDaBrick
    Oct 26, 2021 at 21:05
  • No problem @BobDaBrick, indeed, switch statements are ideally the way to go, however they aren't available in scratch. Oct 27, 2021 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.