To create a variable in a loop with the iteration number

Good morning!

I’m trying to generate many characters at once, with a little randomization. Of course, it means a loop. However I can’t understand how to create a variable in a loop without it being constantly overwritten. I know how to create an array member within a loop, but this time I’d like a variable per character.
So far I can do this manually, but the longer the code, the easier to create errors, and the more uneasy to edit or modify.

<<set $character1 to {
name:$name.random(),
age: 20 + random(1,20) + random(1,20),
}>>
<<set $character2 to {
name:$name.random(),
age: 20 + random(1,20) + random(1,20),
}>>
[...]
<<set $character20 to {
name:$name.random(),
age: 20 + random(1,20) + random(1,20),
}>>

My goal is to achieve something like this:

<<for _i to 1 ; _i < 21 ; _i++>>
<<set $character_i to {
name:$name.random(),
age: 20 + random(1,20) + random(1,20),
}>>
<</for>>

Of course it does not work, because I lack the mean to concatenate _i to $character in order to create variables $character1, $character2, etc. instead of mere strings.

To do what you want, you’d make a small tweak.

Replace

<<set $character_i to {
  STUFF GOES HERE
}>>

with

<<set State.variables["character" + _i] to {
  STUFF GOES HERE
}>>

However, if possible, I’d recommend using an array instead.

<<set $characters = []>>

<<for _i = 0; _i < 20; _i++>>
  <<run $characters.push({
    name: $name.random(),
    age: 20 + random(2, 40),
  })>>
<</for>>

Whatever works best for you.

2 Likes

Many thanks, it works perfectly!