Okay, I have two questions when it comes to arrays. I am creating an array called $inv for inventory. I have a link on the left sidebar to check inventory, and when you click it, it takes you to a room that has
<<print $inv >>
So two questions:
1. When you start the game, I want to display the message "You have nothing" when you click that check inventory link. But once you pick up items, I want it to display the items in the array. How do I create the <<if>><<else if>> statement so it displays one message if the array is empty and another message if the array has objects?
2. Currently, when I do <<print $inv >>, it gives the list like this:
milk,eggs,sugar
I want it to give the list with one object per line so it looks like this:
milk
eggs
sugar
Is there a way to set it to that? Maybe by CSS?
Comments
The inventory checking room now contains this one piece of code:
<<if $inv is 0>>You have nothing.<<elseif>><<print $list = $inv.join('\n');>><<endif>>
It prints "You have nothing" if you haven't picked up anything, and it prints the list in a column if you have.
$inv
will always be an array, and simply may be empty, then you're far better off checking its length, rather than by forcing an equality check against an integer (which requires coercion). Also, you've used<<elseif>>
where you should have used<<else>>
here. For example: Additionally, unless you're using$list
someplace else, there's no reason to assign to it simply to calljoin()
on$inv
. You didn't mention$list
before, so I'm unsure if you actually need it or just think you do. For example:Checking length would be better, especially if a limit was set as to how many items the person could hold. If, let's say, the limit for inventory was 5 items. And when a 6th item was found in the game, the player could decide to drop an existing item (which would splice it from the array) or leave the new object.
Though <<elseif>> is how I've always written this. What is the difference between <<else>> and <<elseif>>?
The difference is that
<<elseif>>
takes a conditional expression (just like<<if>>
), while<<else>>
does not. For example, this is how it is supposed to work: That<<elseif>>
works like<<else>>
when called exactly as<<elseif>>
(no expression or spaces), rather than throwing an error, is a bug in the vanilla story formats (SugarCube does not have this bug). As an exercise, adding a single space after the macro name (i.e.<<elseif >>
) causes it to work as intended, which will throw thebad condition
error because you didn't specify one (i.e. else if what?).http://strugglingwithtwine.blogspot.co.uk/2014/03/handling-inventory.html
The only part I find non-intuitive is removing items from the array. But the following script makes the syntax for that intuitive too: Add that code to a passage tagged [script] and then items can be removed from an array like so: In the preceding example, "$inv" is the array, and 'toothbrush' is a string that is removed from $inv.