# Twine Wiki

### Site Tools

displaying_text_conditionally

This is an old revision of the document!

## Displaying Text Conditionally

Variables can be very handy, but they would be much more useful if they could directly affect the text the reader sees. Consider a passage like this:

You return to Selator's hut. A merry fire is crackling in the kitchen, and something is cooking that smells delicious. He greets you warmly and asks, “Have you got the berry?” If you have got the purple berry of the Antherica plant, turn to 175. If not, turn to 52.

(Steve Jackson and Ian Livingstone, Scorpion Swamp)

It would be nice if the story could track whether the protagonist found the berry or not, and branch accordingly. In order to do this, we need to use conditions. A condition is a kind of expression that evaluates to either true or false. We can use these truth values directly to indicate whether the protagonist found the berries:

```You have no doubt, from Selator's description, that you have found the
Antherica plant. Half your mission is completed. Now you must return to the
village with the precious berry. <<set \$foundBerry = true>>```

Then we can use the `«if»` macro to display a passage indicating victory:

```You return to Selator's hut. A merry fire is crackling in the kitchen, and
something is cooking that smells delicious. He greets you warmly and asks,
"Have you got the berry?"

<<if \$foundBerry>>
"Wonderful!" he exclaims...
<<endif>>```

Anything in between the initial `«if»` and `«endif»` is displayed if the condition is true. You may also include macros inside `«if»` statements, so we could display a longer victory message this way:

```You return to Selator's hut. A merry fire is crackling in the kitchen, and
something is cooking that smells delicious. He greets you warmly and asks,
"Have you got the berry?"

<<if \$foundBerry>>
<<display "Victory">>
<<endif>>```

Our only remaining issue is that if the reader hasn't found the berry, nothing is displayed at all. To remedy this, we can use an `«else»` clause like this:

```You return to Selator's hut. A merry fire is crackling in the kitchen, and
something is cooking that smells delicious. He greets you warmly and asks,
"Have you got the berry?"

<<if \$foundBerry>>
<<display "Victory">>
<<else>>
"That's too bad," he says. "I had such high hopes for you..."
<<endif>>```

`«else»` clauses do the exact opposite as `«if»` ones; they are only displayed if the condition is false. In either case, it's important to remember the `«endif»` at the end; otherwise, it won't be clear where the story should resume.

displaying_text_conditionally.1387094022.txt.gz · Last modified: 2017/10/09 20:37 (external edit)