Is there a better way to check multiple variables

Twine Version:2.3.9
Story Format: Sugarcube 2.31.1

I might be just having a major brain fart because I know there has to be a better way to do what I’m doing, but I can’t think of it.

Here’s my problem:

I’ve got 10 variables:


These variables can have values of 0, 1, or 2.

Is there a way to check these variables en masse? So instead of:

<<if $pInv.book0 is 1 or $pInv.book1 is 1 or $pInv.book2 is 1 or $pInv.book3 is 1 or $pInv.book4 is 1 or $pInv.book5 is 1 or $pInv.book6 is 1 or $pInv.book7 is 1 or $pInv.book8 is 1 or $pInv.book9 is 1>>

I could just have something like:

<<if $pInv.books is 1>>

Further, is there a better way to check these 10 variables to see if None, One, or Multiple of them has a particular value?

So if only one of them has a value of 1, one thing happens, but if two or more have the value of 1, something else happens?

Hopefully that makes sense. Any help would be greatly appreciated.

I’m not a Twine guy so I can’t provide exact code, but:

To avoid the problem of having lots of name+number variables you can instead create a single variable that contains an array (or a named map, where that makes more sense).

Once you have that, you can then write a for loop which, say, sets a temporary variable to false and then loops through all the books and sets the variable to true if any of the books are set to 1 (or whatever condition you’re looking for). Or you set the temporary variable initially to 0 and increment it whenever the condition you’re looking for applies inside the loop, if you’re trying to count how many times it was true instead.

Then you just check the result of that temporary variable after the loop.

JavaScript has some special methods that can count items in an array with a single method call rather than writing your own loop; I’m not sure if SugarCube exposes those or not but for simple conditions that might be an easier option if it does.

Here’s some untested air code generated by glancing briefly at a Sugarcube syntax document. Your mileage may vary.

Somewhere in your story’s initial setup:

<<set $book = [0,0,0,0,0,0,0,0,0,0]>>

(You might need to do something fancier than this in practice, especially if you might want to add more books in a future version of the story and keep the saves compatible.)

When someone acquires the fifth book (arrays are zero-based, for reasons):

<<set $book[4] = 1>>

To count how many books are in state 1:

<<set _books = $book.count(1)>>

To count how many books are in either state 1 or 2 (or more precisely, anything higher than 0):

<<set _books = 0>>
<<for _i, _value range $book>>
<<if _value gt 0>>
<<set _books += 1>>
(do something with _books)

Yep, this is pretty much exactly what I was looking for. Thanks so much!