Use the function command to create your own Lumerical script functions, which allows you to write more reusable, maintainable, and understandable code. User-defined functions support arbitrary input and output variables.
User-defined functions can be defined within your main script file, or saved in separate files, and must be defined at global scope. If you save the function in a separate file, ensure the script file name is different than the function name. It must also be different than any standard Lumerical script functions.
Syntax |
Description |
---|---|
function function_name(input1, input2, ...){ .... return output; } |
The function keyword is used to define a function that can have an arbitrary number of inputs and one output. The return statement is used to specify the output. The function body will be located in between the brackets. |
out=function_name(input1, input2, ...); |
The name of the function is used to call the function and the inputs should be in the same format as the definition. |
Examples
Defining a function that rounds down the input number to the nearest even number
function even_floor(a) { return floor(a) - mod(floor(a),2); }
This function will change the current working directory to the currently opened file directory
function change_to_project_directory() { if(currentfilename != "") { cd(filedirectory(currentfilename )); } }
Functions can also be nested into other function definitions. The following example shows using an add function to create another add function with 4 input arguments:
function add(a, b){ return a+b; } function add4(i, j, k, l){ return add(add(i, j), add(k, l)); }
Note that the function "add" needs to be defined in the global scope, and it won't be recognized if it is defined inside the "add4" function. The following definition of the functions will give an error:
function add4(i, j, k, l){
function add(a, b) {
return a+b;
} return add(add(i, j), add(k, l));
}
Error: add is not a valid function or variable name
Create and call a function saved in a different script file.
Step 1: Suppose the following functions are saved in [[myfunction_library.lsf]].
function func1(x,y) {
return x^2+y^2;
}
function func2(x,y) {
return x*y;
}
Step 2: Run the file that contains the functions to load your functions into the script interpreter. Once the functions are loaded, they can be used in subsequent commands.
myfunction_library;
a=1;
b=2;
?out = func1(a,b) +func2(a,b);
result:
7
See also