0 votes
by (280 points)
Suppose I have a variable with value "[]".  How can I get this to print as []?  Neither print: or text: does the job; each treats the [] characters specially.  The string is from user input and I'd like to be able to faithfully show it.  It may include all sorts of special characters such as * or ` or { and I'd like it to print as is.

I could write a JavaScript function to add appropriate backticks around it, but Harlowe doesn't give me a way to call JavaScript functions (AFAIK).

3 Answers

0 votes
by (280 points)
edited by
 
Best answer

Actually I found that Harlowe does let me call out to JavaScript, except that you can't pass a variable.  Instead you need to use text: to force it into a string.  Then the JavaScript code can do the paranoid checking for backticks and additionally add spaces at the front in back just in case the string starts or ends with a backtick.

(set: $quoted to harloweVerbatim((text: $userInput)))
function harloweVerbatim(str) {
	if (str === undefined || str == "") return "";
	var n = str.length;
	var count = 0;
	var max = 0;
	var delim = "`";
	for (var i = 0; i < n; ++i) {
		var ch = str.charAt(i);
		if (ch == "`") {
			if (++count > max) {
				++max;
				delim += "`";
			}
		} else {
			count = 0;
		}
	}
	var pre = "";
	var post = "";
	if (str.charAt(0) == "`") pre = " ";
	if (str.charAt(n-1) == "`") post = " ";
	return delim + pre + str + post + delim;
}
window.harloweVerbatim = harloweVerbatim; 

 

+1 vote
by (159k points)

You can use the grave / back-tick character functionality of Verbatim markup to output the user input as is.

(set: $userInput to "[]")
(set: $escaped to '`' + $userInput + '`')

User Input: $userInput
Escaped: $escaped

 

by (280 points)
I'm worried this will fail if the user input has a grave character in it.
0 votes
by (6.2k points)

Do this:

(set: $thing to (prompt: 'Input something, user!',''))

(if: $thing is '[]')[`[]`](else:)[$thing]

If you find any other characters it doesn't want to print just make more if statements with backticks.

by (280 points)
That's not practical: the user could type: [`]{``}
...