Howdy, Stranger!

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

Getting the index of an element in an array?

Specifically, I'm trying to make a system for character stats, where a particular character's stats are stored in a datamap as strings, but can be incremented from an array. So for instance:
(set $player to (datamap:
  "dex", "clumsy",
  "str", "weak")
)

(set $dexArray to (a:
  "clumsy",
  "average",
  "nimble")
)

What I'd like to do is to be able to use $player's dex to get the string "clumsy", and then find that string's index in $dexArray so I can increment it by using
(set: $player's dex to $dexArray's (//index of clumsy// + 1)

I know I can get a similar result by using numbers in the datamap (e.g. "dex", 1,) and that does make it easier to increment, but it means that each time I want to print the description of that stat, I have to use
(print: $dexArray's ($player's dex))
instead of a simpler
(print: $player's dex)

I'm currently getting around this by using a passage I named updateVariables that I can (display:) whenever the variables change, which sets the whole
$dexArray's ($player's dex))
to a single variable $dexDesc, but it requires more prep than being able to grab the string directly from the datamap, and it means I have to call that passage any time a variable changes.

Comments

  • You need to state both the name and version number of the Story Format you are using when you ask a questions, as answers can be different for each one. Based on the syntax of your examples I will assume you are using Harlowe, I will also assume you are using the current released version which is 1.2.2

    Harlowe does not currently have a built-in method for obtaining the index of a particular element of an array, you should create an New Issue on the project's website explaining you need for this functionality so that it may be added to a future (the next?) version.

    One way to obtain the index is to use Javascript's indexOf() method instead:
    (set: $array to (a: "A", "B", "C", "D"))
    (set: $index to $array.indexOf('C'))
    Index of C is $index
    
    ... BUT you will need to be aware Javascript and Harlowe use a different base for referencing elements of their array's, which are zero-based and one-based respectively.

    This means that you will need to add one to the value returned from indexOf when using that value to reference the equivalent element in Harlowe code.
    Element in array without adjusting index: (print: $array's ($index))
    
    Element in array after adjusting index: (print: $array's ($index + 1))
    


    Another thing you need to be aware of is what can happen if you don't handle the -1 returned by indexOf if it can't find a particular element.
    (set: $index to $array.indexOf('Z'))
    
    Index of Z is $index
    Element in array using index: (print: $array's ($index))
    
Sign In or Register to comment.