Would it be okay if I asked you a series of really annoying questions that would help me understand why this code works as it does?
My first annoying question is, why does:
random(setup.swordTypes.length - 1)
...need the ".length - 1" bit? To an untrained eye, random(setup.swordTypes) ought to return a random .swordType.
This let's break this question down into two parts: first, let's talk about arrays, then we'll talk about the random() function.
- Arrays hold an ordered collection of data. Each value in an array is mapped to a number. These numbers are called indexes (or indices) ("index" is the singular form).
- Arrays are zero based, meaning the first element in an array is at index 0.
- The length property of an array returns the number of items in an array; it also counts the 0th index.
<<set $array to ['first', 'second', 'third']>>
<<print $array.length>> /% prints 3 %/
<<print $array>> /% prints 'first' %/
<<print $array[$array.length - 1]>> /% prints 'third' %/
/% $array.length = 3, $array.lingth - 1 = 2, since 0 if first item, 2 is third/last item %/
<<set $otherArray to ['hello']>>
<<print $otherArray.length>> /% 1 %/
<<print $otherArray>> /% 'hello' %/
<<print $otherArray[$otherArray.length - 1]>> /% 'hello' %/
<<print $otherArray[$otherArray.length]>> /% nothing, since this index is empty %/
The random() function.
In SugarCube, the random function accepts up to two numbers, and returns a random whole number between those values.
<<set _diceRoll to random(1, 6)>> /% returns a number between 1 and 6 %/
If the first number is omitted, it sets the first value to 0.
<<set _diceRoll to random(6)>> /% returns a random number between 0 and 6 %/
So, the reason I'm using random on the length - 1 is because I want to get the number of an index from the array. I then use this number to access the array and form the description, and further use this number to set the quality/price of the generated item: a higher index means it pulls a higher quality option from the array, so the price should be higher.
There is an Array.random() method that we could use instead to return random values from the array, but I wanted the number as well. The random() function we used only accepts numbers.
Does that make sense?