# Parsing numbers manually

My tests for Kerkerkruip now include checking the correctness of numerical expressions - the output text is captured, and then numbers are parsed and evaluated. To do this, I have written these phrases:

[spoiler][code]To decide what number is digit (T - a text):
Repeat with value running from 0 to 9:
if character number (value + 1) in “0123456789” is T:
decide on value;

To decide what number is (T - a text) as a number:
Let the sign be 1;
Let the value be 0;
if T matches the regular expression “+”:
replace the regular expression “<^+>+" in T with “”;
if T matches the regular expression “-”:
replace the regular expression "<^->
-” in T with “”;
now the sign is -1;
while T matches the regular expression “^\D*(\d)”:
now the value is (value * 10) + digit (text matching subexpression 1);
replace the regular expression “^\D*\d” in T with “”;
decide on the sign * the value;
[/code][/spoiler]

The tests are running really slowly, and I wonder if this is part of the reason. Is there a way to make use of parser routines to do this parsing for me? Or a way to make things run faster? I don’t know how fast Inform is at processing regular expressions, but I’ve been doing a lot of it and it might be worthwhile to know how to optimize them.

Any suggestions would be welcome - thanks in advance!

Regular expressions are really overkill for this task. I’ve been using this one from the Guncho Mockup extension:

``````To decide which number is numeric value of (T - indexed text):
let S be 1;
let L be the number of characters in T;
if L is 0, decide on 0;
let negated be false;
if character number 1 in T is "-" begin;
let negated be true;
let S be 2;
end if;
let result be 0;
repeat with N running from S to L begin;
let C be character number N in T;
let D be 0;
if C is "1" begin; let D be 1; otherwise if C is "2"; let D be 2;
otherwise if C is "3"; let D be 3; otherwise if C is "4"; let D be 4;
otherwise if C is "5"; let D be 5; otherwise if C is "6"; let D be 6;
otherwise if C is "7"; let D be 7; otherwise if C is "8"; let D be 8;
otherwise if C is "9"; let D be 9; otherwise if C is "0"; let D be 0;
otherwise; decide on 0; end if;
let result be (result * 10) + D;
end repeat;
if negated is true, let result be 0 - result;
decide on result.``````

It’s more code but I suspect it’s noticeably faster.

Also, this is probably faster or at least as fast as the “what number is digit” code so it might not be necessary to have a separate phrase for that.

Thanks! I got rid of most of the regexes and now it’s a LOT faster.