Custom Functions (Hack)

script

#1

In Lumerical there isn’t a way to create custom functions.
I present here some hacks I use to do so.

First the most obvious approach:

A = 1; B = 2;
customAdd = '?A + B;';
eval(customAdd);

Which returns 3. You can just use this combination of predefining some input variables, A,B, and them run the script. Therefore later you can do:

A = 1; B = 1;
eval(customAdd);

Which will return 2. But if you want a function which parameter is a variable to be set, for example. A = 'lambda' and value=32, you want a function that set A=value making the substitution first.

The obvious try is:

A = 'lambda'; value = 32;
customSet = 'eval(A) = value;';
eval(customSet);

This does not work. Chaking the function to customSet = 'A = value;';, makes A=32, instead of lambda.
The “proper” way of doing so is:

A = 'lambda'; value = 32;
customSet = "replacestring('@1 = value;', '@1', A);";
eval(customSet);

Where you first replace A to lambda and then evaluate the string.
Later you can:

A = 'lambda'; value = 32;
eval(customSet);

But things get messy when you have lots of parameters. Another way to acomplish this is the following:

param = struct;
setVariable = "
  temp = '@1 = @2;';
  temp = replacestring(temp, '@1', param.var);
  temp = replacestring(temp, '@2', num2str(param.value));
  eval(temp);
"; 

Them you can use:

param.var = 'lambda'; param.value = 32;
eval(setVariable);

To set the variable.