s = invoke(function_nameʃ, argument1, ..., argumentNʅ);
s = invoke(function_name, arguments := arguments_json);
The
invoke function allows you to execute
user-defined functions using runtime binding (where the function name is only evaluated at runtime). When compiling an application, the CSPro compiler only knows about functions declared up to the point where a function call is coded, so for more dynamic applications, it can be a challenge to manage function calls when you would like to call a function declared after the point of the call. One workaround is to use
function pointers; the
invoke function provides another way to bypass the CSPro compiler limitation.
The
invoke function evaluates the string expression
function_name at runtime, not compile-time. In the function's first version, zero, one, or more arguments are provided directly at compile-time. At runtime, the arguments are checked against the function's parameters, and if they are compatible, the function call is executed.
The function's second version, using
named arguments, allows arguments to be passed using the string expression
arguments_json. This text is a
JSON string containing the arguments to the function. This string is evaluated as an object, with each of the object's names matched with the name of a function parameter, and the value is bound to that parameter using the rules for
representing symbols in JSON.
The function returns the return value of the user-defined function as a string when successful, and a blank string otherwise. If the function has a numeric return value, the value is converted to a string, which you can convert back to a number using the
tonumber function.
function numeric ManipulateValues(numeric value1, numeric value2,
string function_name = "AddValues")
string result = invoke(function_name, value1, value2);
exit tonumber(result);
end;
function AddValues(numeric value1, numeric value2)
exit value1 + value2;
end;
function MultiplyValues(numeric value1, numeric value2)
exit value1 * value2;
end;
// ...
ManipulateValues(16, 16); // 32
ManipulateValues(16, 16, "MultiplyValues"); // 256
ManipulateValues(16, 16, "DivideValues"); // runtime error (DivideValues function does not exist)
invoke("ManipulateValues", 16, 16); // "32"