Twine 1.42
SugarCube 2.5
I'm not sure how to even explain this, so I hope it makes sense.
I'd like to create sort of random NPCs. They will have a name and traits that are assigned randomly from pre-created lists.
So the array of objects would be something like:
code
<<set $NPCs to [
{
firstname: "Mark",
lastname: "Martin",
haircolor: "Brown",
eyecolor: "Brown,"
},
{
firstname: "Brad",
lastname: "Johnson",
haircolor: "Blue",
eyecolor: "Brown,"
}
/code
I can do that, but I'd like the NPCs to be different on any given play through, they are filler, not the main characters.
So I created array lists and tried to insert their information randomly, which works if I already created an array with the number of possible index values.
code
<<nobr>><<set $RandomMaleNames to [
"Jeff",
"Ryan",
"Donald",
"Alexander",
"Lewis",
"Xavier",
"Brad",
"Theron",
"Bernie",
"Lee"
]>>
<<set $lastnames to [
"Li",
"Smith",
"Lam",
"Martin",
"Brown",
"Roy",
"Tremblay",
"Lee",
"Gagnon",
"Wilson"
]>>
<<set $NPCs to [
{
firstname:"Boo",
lastname: "Boo"
},
{
firstname:"Boo",
lastname: "Boo"
}, {
firstname:"Boo",
lastname: "Boo"
}, {
firstname:"Boo",
lastname: "Boo"
}, {
firstname:"Boo",
lastname: "Boo"
}, {
firstname:"Boo",
lastname: "Boo"
}, {
firstname:"Boo",
lastname: "Boo"
}, {
firstname:"Boo",
lastname: "Boo"
}, {
firstname:"Boo",
lastname: "Boo"
}
]>>
<<set $namecounter to $lastnames.length>>
<</nobr>>
<<for $i to 0; $i lt $namecounter; $i++>>\
<<set $NPCs[$i].firstname to $RandomMaleNames.random()>>\
<<set $NPCs[$i].lastname to $lastnames.pluck()>>
<<print $NPCs[$i].firstname>> <<print $NPCs[$i].lastname>>
<</for>>
/code
So this code creates 9 NPCs with different last names, but they can share the same first name.
It appears to work, except for the tenth name. Which I intentionally left off to demonstrate the problem. I get the errors:
code
Error: <<set>>: bad evaluation: Cannot set property 'firstname' of undefined Error: <<set>>: bad evaluation: Cannot set property 'lastname' of undefined
Error: <<print>>: bad expression: Cannot read property 'firstname' of undefined Error: <<print>>: bad expression: Cannot read property 'lastname' of undefined
/code
Which I assume is because there isn't a tenth spot. If I add a tenth one to the $NPCs array all errors go away.
This is fine, I can work with it, but I was wondering if there was a better way. One in which if I added more last names the array would grow without me needing to manually add to the NPCs array.
If anyone should notice any non-related errors that will bite me later I'd appreciate the heads up too.
Comments
The following demonstrates the setting up of the $NPCs array and the <<for>> macro, it assumes everything else is the same as your example.