Skip to main content

How to replace part of the variable

You will learn in this lesson how you can use the Conditions block to replace a part of a variable. This can be useful, for example, if you want to build a gaming logic or provide some bonus terms to a client.

Example of variable replacement

For example let’s build a game where we replace the contents of the backpack.

Declare a variable

Add the Conditions block and add $backpack = "sword, empty bottle, dragon tooth, fern flower, parchment roll"

You just have created a $backpack variable and added the backpack contents to it.

Create a connection from the Condition to a new Text block with the following contents:

Hello! You have $backpack in your backpack.

Add another Text block to the same screen. Copy and paste the following into it:

You are now standing near a stream. A perfect chance to get some water.

Add an Intent that contains get water to the same screen.

You can also use the template syntax to add more phrase variations that can be used by the user.

Add a new screen with the Conditions block. Copy and paste the following into the Conditions block:

$backpack = $backpack.replace ("empty bottle", "bottle of water")

In this case, only the first item from the list will be replaced.

To replace multiple items, use, for example, the $backpack= $backpack.replace ("water", "wine") condition.

In this case all the water occurrences will be replaced with wine. And if you had a bottle of water and a glass of water, you will now have a bottle of wine and a glass of wine.

So:

  • we have modified the variable by replacing its part
  • as we cannot actually modify the variable, we have to recreate it using the = operator

Associate the Condition with the next Text block with following contents:

Done! You now have $backpack in your backpack

The final script looks like this:

If you test the script, you’ll get the following: