Skip to content
davedelong edited this page Sep 27, 2011 · 5 revisions

There are several ways to evaluate strings, depending on how much customization you want to do. Most of these options require an NSError ** parameter, although some do not.

  • If you use one of the options that does not accept an NSError **, then any tokenization, parsing, or evaluation errors will be NSLogged.
  • If you use one of the options that does accept an NSError **, then you must supply one. Failing to do so will probably result in a crash.

Regarding Whitespace

Until recently, whitespace was ignored in evaluated strings. This meant that @"3 4" was the same as @"34". However, whitespace is now seen as a logical break in the token stream. Now, @"3 4" will be parsed as the 3 token followed by the 4 token. And because of the logic in recognizing implicit multiplication, a multiplication operator will be injected into the stream. Now, @"3 4" is recognized as @"3*4", or 12.

NSString

NSLog(@"%@", [@"1 + 2" numberByEvaluatingString]);

Useful for the simplest evaluations (ie, no variables). Uses the [DDMathEvaluator sharedMathEvaluator] and all functions registered with it.

NSString with substitutions

NSDictionary *s = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:42] forKey:@"a"];
NSLog(@"%@", [@"1 + $a" numberByEvaluatingStringWithSubstitutions:s]);

Also:

NSDictionary *s = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:42] forKey:@"a"];
NSError *error = nil;
NSLog(@"%@", [@"1 + $a" numberByEvaluatingStringWithSubstitutions:s error:&error]);

Useful for specifying variable substitutions. Uses the default [DDMathEvaluator sharedMathEvaluator].

DDExpression

NSError *error = nil;
DDExpression *e = [DDExpression expressionFromString:@"1 + 2" error:&error];
NSLog(@"%@", [e evaluateWithSubstitutions:nil evaluator:nil]);

Useful for specifying variable substitutions or a custom evaluator.

DDMathEvaluator

DDMathEvaluator *eval = [DDMathEvaluator sharedMathEvaluator];
NSLog(@"%@", [eval evaluateString:@"1 + 2" withSubstitutions:nil]);

Useful for specifying variable substitutions or a custom evaluator.

DDParser

NSError *error = nil;
DDParser *parser = [DDParser parserWithString:@"1 + 2" error:&error];
DDExpression *e = [parser parsedExpressionWithError:&error];
NSLog(@"%@", [e evaluateWithSubstitutions:nil evaluator:nil error:&error]);

Useful for specifying a custom parser or custom operator associativities, specifying variables, or specifying a custom evaluator.

DDMathStringTokenizer

NSError *error = nil;
DDMathStringTokenizer *t = [DDMathStringTokenizer tokenizerWithString:@"1 + 2" error:&error];
DDParser *parser = [DDParser parserWithTokenizer:t error:&error];
DDExpression *e = [parser parsedExpressionWithError:&error];
NSLog(@"%@", [e evaluateWithSubstitutions:nil evaluator:nil error:&error]);

Useful for specifying a custom tokenizer.

Clone this wiki locally