# Changing the value of randomly selected strings from a list

In my game I have stats and skills variables, both of which are numbers (e.g. \$stat1 = 5)

I would like in some situations for a stat to be randomly selected and changed (e.g. \$stat2 is chosen at random and then \$stat2 = \$stat2 - 1).

I can change the value when it's not randomly selected, and I can randomly select a value, but I can't figure out how to combine them.

``````<<set \$r = [\$stat1, \$stat2, \$stat3]>>
<<set \$r2 = \$r.random()>>

<<if (\$skill1 + random(1,6)) > 5>>
You win! [[next]]

<<else>>

**something goes here**

[[previous]]

<<endif>>``````

+1 vote
by (8.6k points)
selected

I would start by redesigning how you save your stats. Put them in a separate object and acess them by name. You need to make sure the object is initialised first, somewhere in StoryInit or so. And make sure you don't overwrite the current value.

``<<set \$stats = \$stats || {}>>``

Now you can access stats in two ways. Both are equivalent, so use whatever fits better.

``````<<set \$stats.str = 12>>
<<set \$stats["str"] = 12>>``````

``````<<set \$r = ["str", "dex", "cool"]>>
<<set \$r2 = \$r.random()>>

<<if \$stats[\$r2] + random(1, 6) > 5>>
...
<</if>>``````

But now \$stats [\$r2] lets you modify the stat value too.

``<<set \$stats[\$r2] -= 1>>``

by (160 points)
Great! Thank you!

What does the || mean?
by (8.6k points)

It technically is the JavaScript boolean "or" operator.

Practically, it works by first evaluating the left side and returning that value if it isn't "falsey", else returning whatever is on the right side. An undefined variable is by definition "falsey" while any object - including empty ones - by definition isn't. This means that "\$obj || {}" returns whatever is in \$obj when it was already set, else the empty object {}.

The result is that <<set \$obj = \$obj || {}>> sets \$obj to itself if it is already set (basically, doing nothing), else initialises it with {}. It's the shorter and faster version of writing ...

``````<<if def \$obj>>
<<set \$obj = \$obj>>
<<else>>
<<set \$obj = {}>>
<</if>>``````