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.