0 votes
by (8.8k points)

I have an array called $npc.options.  I'm using the push() method to populate it at various points in the game.

I'd like the array to only ever contain unique values.  I guess I can use <<if>> statements like so:

<<if $npc.options.includes("attackPC")>>
  <<set $npc.options.push("attackPC")>>

But is there a simpler way to do it?  Something like:

<<set $npc.options.uniquepush("attackPC")>>


1 Answer

+1 vote
by (65.8k points)
selected by
Best answer

First.  There's no reason to ever have an empty case.  Your initial code sample should be using the not operator.  For example:

<<if not $npc.options.includes("attackPC")>>
  <<set $npc.options.push("attackPC")>>

As far as a simpler way, you could use a Set instead of an Array.  Sets require that all members be unique—i.e. there can only be one such member.  For example:

/* Initializing $npc.options as a Set. */
<<set $npc.options to new Set()>>

/* Adding a member to the Set. */
<<run $npc.options.add("attackPC")>>

/* Removing a member from the Set. */
<<run $npc.options.delete("attackPC")>>

/* Checking for the existence of a member. */
<<if $npc.options.has("attackPC")>> ...attackPC exists... <</if>>

/* Checking for the non-existence of a member. */
<<if not $npc.options.has("attackPC")>> ...attackPC does not exist... <</if>>


by (8.8k points)
Thanks Exile, both for the advice on Sets and the not operator.  :-)
Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.