Need Help with Harlowe 3: Modifying a String or Array

Twine 2.3.13 (latest release)
Harlowe 3.2.2

I’m really struggling with what I feel like is a simple coding task in my story: I want to either

  • take a string generated by a variable and replace the 1st through nth character with another character
  • take an array generated by a variable and modify the 1st through nth value with another value

Either one of these will work perfectly. I’ve struggled for many hours looking at the Harlowe documentation and nothing I’ve tried is working. I can’t get the lambda commands like (altered:) to work with a conditional. For example,
(set: int-type $maxHearts to 4) (str:...(altered: str-type _icon via _icon + "x", ...(repeated: $maxHearts, "∙ ")))
Generates " ∙ x∙ x∙ x∙ x" which is essentially what I want, but instead of appending x to every "∙ ", I want to replace some of them with another character.
The Harlowe documentation suggested using a condition such as (their example) (cond: pos is an odd, it, it + (str:pos)) with (altered:) which in this case would output odd-numbered strings, but I can’t figure out how to use those two together. I don’t see anywhere in the (altered:) lambda syntax that would accept a conditional or even do anything besides appending something to every string. I don’t see how to feed the array (altered:) returns into something that will accomplish my task, either.

At this point I would even be open to Javascript solutions.

Thank you so much for reading this far. I’m grateful for any help or advice!

I may be misunderstanding your requirements, but I believe the you can use the (substring:) macro combined with the (str-repeated:) macro, and the (subarray:) macro combined with the (repeated:) macro, to achieve the outcome you want.

<!-- Dynamically create a String of a specific length. -->
(set: $string to (str-repeated: 10, "."))
<!-- Dynamically create an Array of a specific length. -->
(set: $array to (repeated: 10, "."))

original string: $string
original array: (joined: "", ...$array)

<!-- the nth value -->
(set: $nth to 5)

<!-- Replace the 1st to nth characters of the String. -->
(if: $nth < $string's length)[
	(set: $string to (str-repeated: $nth, "x") + (substring: $string, $nth + 1, $string's length))

<!-- Replace 1st to nth elements of the Array. -->
(if: $nth < $array's length)[
	(set: $array to (repeated: $nth, "x") + (subarray: $array, $nth + 1, $array's length))

new string: $string
original array: (joined: "", ...$array)
1 Like