evaluateFunctionString method

Object evaluateFunctionString(
  1. String functionName,
  2. StringBuffer? textOutput, [
  3. List<Object> arguments = const []
])
Evaluates a function defined in ink, and gathers the possibly multi-line text as generated by the function. This text output is any text written as normal content within the function, as opposed to the return value, as returned with `~ return`. The name of the function as declared in ink. The text content produced by the function via normal ink, if any. The arguments that the ink function takes, if any. Note that we don't (can't) do any validation on the number of arguments right now, so make sure you get it right!

Implementation

Object evaluateFunctionString(String functionName, StringBuffer? textOutput,
    [List<Object> arguments = const []]) {
  _logger.finest('[evaluateFunctionString] $functionName');
  if (onEvaluateFunction != null) {
    onEvaluateFunction?.call(functionName, arguments);
  }
  ifAsyncWeCant('evaluate a function');

  if (isBlank(functionName)) {
    throw Exception('Function is empty or white space.');
  }

  // Get the content that we need to run
  var funcContainer = knotContainerWithName(functionName);
  if (funcContainer == null) {
    throw Exception("Function doesn't exist: '" + functionName + "'");
  }

  // Snapshot the output stream
  var outputStreamBefore = List<RuntimeObject>.of(state.outputStream);
  _state.resetOutput();

  // State will temporarily replace the callstack in order to evaluate
  state.startFunctionEvaluationFromGame(funcContainer, arguments);

  // Evaluate the function, and collect the string output
  while (canContinue) {
    textOutput?.write(Continue());
  }

  // Restore the output stream in case this was called
  // during main story evaluation.
  _state.resetOutput(outputStreamBefore);

  // Finish evaluation, and see whether anything was produced
  var result = state.completeFunctionEvaluationFromGame();
  if (onCompleteEvaluateFunction != null) {
    onCompleteEvaluateFunction?.call(
        functionName, arguments, textOutput.toString(), result);
  }
  return result;
}