Howdy, Stranger!

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

[Harlowe]Convert a string from (prompt:) into a number

Heal Up(click: "Heal Up")[(set: $Hgain to (prompt: "How many of your crumbs would you like to use?"))(set: $Health to it + $Hgain)(set: $Crumbs to it - $Hgain)]

So the user inputs the number of $Crumbs they want to use to heal. The issue is that (prompt:) takes the input as a string. I need it as a number. Anything I can do, or should I go a different route? I have an alt way prepped, but I wanted to see if I could do something a little more special

Comments

  • edited August 2016
    note: I am going to assume you want the number to be an Integer (no decimal point) and that you want the number to be positive.

    There are two issues with converting the return value of (prompt:) to an Integer:

    1. The Reader may click the Cancel button or click the OK button without entering a value.

    2. The Reader may enter a value that is not a positive integer.
    eg. 12.34, -23, asdj, #(@jd83, etc...

    The following code demonstrates the core steps needed to solve these issues, for the example I suggest placing it within a new passage named Convert Hgain to Integer
    {(if: $Hgain is "" or isNaN($Hgain) or !isFinite($Hgain))[
    (set: $Hgain to 0)
    ] (else:)[
    (set: $Hgain to Math.abs(parseInt($Hgain)))
    ]}
    
    ... the above first checks if a value was entered, then if the value is a number of any sort, then if the number is within a Finite range. If any of these checks fail then Hgain is set to zero. If the checks pass then the value is first converted into an Integer and then forced to be a positive integer.

    The following is a modified version of your example showing how to use the Convert Hgain to Integer passage, it also includes some extra code to show the change to the $Health and $Crumbs variables which you can remove. I also used collapsing markup to make the example more readable.
    {
    (set: $Health to 10)
    (set: $Crumbs to 10)
    }[Health: $Health, Crumbs: $Crumbs]<stats|
    
    Heal Up(click: "Heal Up")[{
    (set: $Hgain to (prompt: "How many of your crumbs would you like to use?"))
    (display: "Convert Hgain to Integer")
    (set: $Health to it + $Hgain)
    (set: $Crumbs to it - $Hgain)
    } (replace: ?stats)[Health: $Health, Crumbs: $Crumbs] ]
    
  • @greyelf it's been a while (and I'm not sure if anything in Harlowe 2 changed when you initially wrote this?) but this doesn't seem to be working for me: the variable is always returned as NaN. I think the issue is that whatever input the player enters is returned automatically as a string, and attempting to punch that string into parseInt returns NaN in response.

    But maybe I'm doing something wrong?
Sign In or Register to comment.