Skip to content

Adding New Functions

Dave DeLong edited this page Oct 7, 2011 · 3 revisions

Registering new functions is easy. You just need a block and a string. So for example:

DDMathFunction function = ^ DDExpression* (NSArray *args, NSDictionary *variables, DDMathEvaluator *evaluator, NSError **error) {
  if ([args count] != 1) {
    //fill in *error and return nil
  }
  NSNumber * n = [[args objectAtIndex:0] evaluateWithSubstitutions:variables evaluator:evaluator error:error];
  NSNumber * result = [NSNumber numberWithDouble:[n doubleValue] * 42.0f];
  return [DDExpression numberExpressionWithNumber:result];
};
[[DDMathEvaluator sharedMathEvaluator] registerFunction:function forName:@"multiplyBy42"];

NSLog(@"%@", [@"multiplyBy42(3)" numberByEvaluatingString]);  //logs "126"

You may unregister any functions you have added this way. You cannot unregister built-in functions, nor can they be overridden.

Function names can consist of letters, digits, or underscores, but cannot be composed solely of digits (otherwise they'd be interpreted as numbers). They are case-insensitive. (mUlTiPlYbY42 is the same as multiplyby42)

Functions are registered with a specific instance of DDMathEvaluator. The simplest approach is to register everything with the shared instance ([DDMathEvaluator sharedMathEvaluator]). However, should you only need certain functions available in certain contexts, you can allocate and initialize any number of DDMathEvaluator objects. All math evaluators recognize the built-in functions.