Skip to content


Subversion checkout URL

You can clone with
Download ZIP

Adding New Functions

Dave DeLong edited this page · 5 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 defaultMathEvaluator] registerFunction:function forName:@"multiplyBy42"];

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

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 default instance ([DDMathEvaluator defaultMathEvaluator]). 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.

Something went wrong with that request. Please try again.