Custom Function Development

Top  Previous  Next

MScript is an extensible language. New functions can be developed with Java by implementing org.moremotion.evaluator.MSciptFunction interface.

Assume that we need a new function called repeat() that repeats the given string the given number of times and returns it. The example below shows how we want to use it.

  @echo( '*** ' + repeat('-', 50) + ' ***' )

The definition of the function is done in the configuration as follows.

  <mscriptFunction name="repeat">

    <class>mypack.RepeatMScriptFunction</class>

    <param name="repeat-separator">,</param>

  </mscriptFunction>

 

And the source code of the mypack.RepeatMScriptFunction class s as follows.

 

  package mypack;

 

  import org.moremotion.evaluator.*;

 

  public class RepeatMScriptFunction implements MScriptFunction {

 

    public Object execute(Expression[] params, MScriptFunctionContext msfc) 

    throws MScriptFunctionException {

 

      try {

 

        if (params.length < 2) {

          throw new MScriptFunctionException("Less parameters than expected");

        }

        MMSymbolResolver sr = msfc.getSymbolResolver();

        String separator = msfc.getMScriptFunctionConfig().getParameter("repeat-separator").stringValue(null);

        String s = params[0].evaluate(sr).toString();

        int times = ((Double)params[1].evaluate(sr)).intValue();

        StringBuffer result = new StringBuffer();

        for (int i = 0; i < times; i++) {

          if (result.length() > 0) result.append(separator);

          result.append(s);

        }

        return result.toString();

 

      } catch(Exception ex) {

        throw new MScriptFunctionException(ex);

      }

 

    }

  }

 

The execute method of the class is called by MScript engine and function parameters are passed in a Expression array. The second parameter of the method is a MScriptFunctionContext object which provides access to all the other necessary objects.

See how MScript configuration is acquired and the value of the "repeat-separator" parameter is accessed through the MScriptFunctionContext object.