Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Adding sentences to Arrays

Hello there.

I've using the following code to contain and display information about npc's during my game:
<<set $npcs to {
		barkeeper:{name: "Unknown",
					interaction: 0,
					aff: "",
					related:"",
					remarks:"",
					visible:false,
					},
		waitress:{name: "Unknown",
				interaction: 0,
				aff: "",
				related:"",
				remarks:"",
				visible: false,}
}>>

And it's been working great.
Now, I've been setting new variables like so:
<<set $npcs["barkeeper"].name to "Ric">>
Which works fine when it's a just a name, for example.
But in the case, let's say of
$npcs["barkeeper"].remarks
I would like to add multiple sentences. My intention, was that during the game, when you discovered a new detail about the character I would add it to this variable so that it could be displayed later. Something like "he likes beer", "he does not like blonds", and so on and on. Now this may be a totally dumb question, but I don't know how to add new sentences to the array, only set it as something completely new.

I feel like it's just a matter of syntax that I'm not familiar with, but I would love any assist. Thanks!
(and I've been using Twine 2 and Sugarcube 2.18)

Comments

  • You need to do two things.

    1. Make sure to initialize the array. The best way is to use an empty array literal, which is an empty pair of brackets ( [] ).
    <<set $npcs to {
    		barkeeper:{name: "Unknown",
    					... 
    					remarks: [],
    					...
    					},
    		... 
    			
    }>>
    

    2. To add items, use the <array>.push() method:
    <<run $npcs.barkeeper.remarks.push('likes beer')>>
    
  • Again Chapel, you save the day! Thanks for the simple and incredibly fast response. This will be really useful!
  • A little follow-up.
    When I use the push method it creates commas in the array. Is it possible to remove them? Because I'm adding sentences and having them ending with a dot and then a comma just looks weird... (e.g."Likes beer.,Does not like blonds."). It's just a small whim of mine... :tongue:
  • There are no commas in the array. You sound like your attempting to print the array as-is, which is why you're seeing the separators—that's the default separator used when an array is converted to a string.

    Try something like the following instead, which uses the <Array>.join() method to convert the array into a string with a separator of your choosing:
    <<print $npcs.barkeeper.remarks.join(" ")>>
    
    The quotes in the above contain a single space.
  • Perfect @TheMadExile ! Thank you!
Sign In or Register to comment.