menu
Menu
Drakon.Tech logo
Drakon.Tech
Get started
Drakon.Tech documentationProgramming in DRAKONThe basics of programming with Drakon.TechAdvanced programming methodsGame examplesThe source codeLegacy tutorials (JavaScript 0.2)Tutorial 1. Hello world!Tutorial 2. Variables and functionsTutorial 3. Basic flow controlTutorial 4. ChoiceTutorial 5. For each loopTutorial 6. The arrow loopTutorial 7. SilhouetteTutorial 8. Lambdas and exceptionsTutorial 9. ModulesTutorial 10. Concurrent programming with scenariosExamplesLibraries

Tutorial 4. Choice

The Choice icon compares an expression to several values. We could use a sequence of Question icons, but Choice is a more concise option for this case. The Choice icon is the equivalent of the switch statement in JavaScript.

Let's take the printNumber function from the previous tutorial. Here, we compare the number variable to values 10 and 20.

A more complex decision tree with the Question icon

Let's rewrite this function with a Choice icon.

The Choice icon

Note that the expression in the Choice icon will be evaluated only once.

We put each of the values in a separate case icon. We can add more case icons if we want. The empty icon to the right means "all other values."

Let's build and run the project.

10 "ten"
20 "twenty"
30 "some other value"

If we delete the empty Case icon, Drakon.Tech will add a throw statement for all other values besides 10 and 20.

The Choice icon

Let's test it. Right! We get an error: "unexpected choice value."

10 "ten"
20 "twenty"
tutorial_04_choice.js:18 Uncaught Error: Unexpected Choice value: 30
    at printNumber (tutorial_04_choice.js:18)
    at main (tutorial_04_choice.js:7)
    at tutorial_04_choice.js:24
    at tutorial_04_choice.js:26

Case icons can contain any expressions, not only constants. Let's put a variable in it instead of a constant.

The Choice icon with a variable in a Case

See, we get the same result as before.

10 "ten"
20 "twenty"
30 "some other value"
close
Close
Drakon.Tech logo
Drakon.Tech home
Programming in DRAKONThe basics of programming with Drakon.TechAdvanced programming methodsThe source codeLegacy tutorials (JavaScript 0.2)