sleep.interfaces
public interface Function extends Serializable
A function bridge is used to define a built-in function. Once a function bridge is installed into the script environment, it can be called from user created scripts.
An example of a function bridge:
public class MyAddFunction implements Function { public Scalar evaluate(String name, ScriptInstance script, Stack arguments) { if (name.equals("&add")) { int a = BridgeUtilities.getInt(arguments, 0); int b = BridgeUtilities.getInt(arguments, 0); return SleepUtils.getScalar(a + b); } return SleepUtils.getEmptyScalar(); } }
To install a function into a script environment:
ScriptInstance script; // assume Function myFunctionBridge = new MyAddFunction(); Hashtable environment = script.getScriptEnvironment().getEnvironment(); environment.put("&add", myFunctionBridge);
In the above code snippet the script environment is extracted from the ScriptInstance object script. The function name is the key with the instance of our Function bridge as the value. The function name must begin with & ampersand for sleep to know it is a function.
Once a function bridge is installed into the script environment. The installed function(s) can be called as normal sleep functions i.e.
$var = add(3, 4); # value of $var is now 7
To evaluate a Function object (should you ever need to directly evaluate one):
// assume Function func; ScriptInstance script; Stack locals Scalar value = SleepUtils.runCode(func, "&name", script, locals);
The above is important because it clears the return value in the script environment once the function finishes executing. Failing to clear the return value can result in other sleep code not executing at all. It is not a fun bug to track down.
See Also: BridgeUtilities ScriptInstance SleepUtils
Method Summary | |
---|---|
Scalar | evaluate(String functionName, ScriptInstance anInstance, Stack passedInLocals)
Evaluate a function and return the resulting scalar. |
Parameters: functionName the function being called. anInstance an instance of the script calling this function. passedInLocals a stack containing the locals passed to this function. The locals are Scalar values passed in reverse order i.e. [arg n, arg n-1, ..., arg 1, arg 0]
Returns: an instance of Scalar containing the return value of this function.