Topic: How to accept user input via prompt: and then convert that input into a number.
My set-up:
Twine Version: 2.3.14 (2.3.14)
Story Format: Harlow 3.2.2
(For some reason, I had a difficult time figuring this out - so I’m posting my solution here in case it helps anyone else. Hopefully the long-arms of google will crawl this post)
The trick is to use the (num: ) macro
https://twine2.neocities.org/#macro_num
Example
{
(set: $age to (prompt:“How old are you?”, “”))
}
(set: $age2 to (num: $age))
(set: $mathcheck to ($age2 + 10))
the age you entered is $age
converted to a number value: $age2
My math check is $mathcheck (to verify that I now have an integer)
(if: $age2 is <= 18 )[Sorry, you’re too young!]
(else:)[You can continue]
1 Like
Well done.
I have a couple of suggestions, most are optional.
1: Please use the </>
option in the comment field Toolbar when including code examples in your posts, it makes those example easier to read / copy-n-paste and stops the forum’s software converting valid Standard quotes into invalid Typographical (curvy) quotes.
eg. wrapping your entire example within </>
would result in it looking so…
{
(set: $age to (prompt: "How old are you?", ""))
}
(set: $age2 to (num: $age))
(set: $mathcheck to ($age2 + 10))
the age you entered is $age
converted to a number value: $age2
My math check is $mathcheck (to verify that I now have an integer)
(if: $age2 is <= 18 )[Sorry, you’re too young!]
(else:)[You can continue]
2: You could include the 2nd and 3rd (set:) macro calls within the Collapsing whitespace markup, which would stop them from adding additional blank lines to the example.
3: You don’t need the open and close parentheses/brackets around your $age2 + 10
addition.
4: You shouldn’t use the is keyword comparison operator when using mathematical comparison operators like <= because the is operator means exactly equal to, and logically a value can’t be exactly equal to and less than or equal to at the same time.
note: The only reason your $age2 is <= 18
conditional expression doesn’t result in an error is because Harlowe was enhanced to ignore that specific error.
The following is a variation of your own example with the above suggestions added to it.
{
(set: $age to (prompt: "How old are you?", ""))
(set: $age2 to (num: $age))
(set: $mathcheck to $age2 + 10)
}
the age you entered is $age
converted to a number value: $age2
My math check is $mathcheck (to verify that I now have an integer)
(if: $age2 <= 18)[Sorry, you’re too young!]
(else:)[You can continue]
3 Likes
Thanks for the tips, Greyelf!