Reputation: 715
I use the code
clc;
clear;
getd();
a=1;
b=myFunction();
, where myFunction
is defined by
function b=myFunction()
b=a+1;
endfunction
. For some strange reason, this works just fine in Scilab. I believe myFunction
simply inherits a
from the main function. This is in contrast with for instance Matlab, where a
needs to be an input argument of myFunction
in order to use it.
I want functions in Scilab to only work with local variables and variables given as input, like in Matlab. So that in this case a
is not inherited from the main function.
How can I achieve this?
Upvotes: 1
Views: 579
Reputation: 11
You can avoid this by choosing distinct names for variables you wish to be local. Like putting a myFunction_ in front of all the local variable names. In your example, you would rename a into myFunction_a. Unfortunately, I don't know if it would be possible to write a script that would do the work for you in case you have large matlab scripts.
Upvotes: 0
Reputation: 61
This works fine in Scilab because in case a function uses an undefined variable the interpreter search it in the calling scope. Although it seems strange, this is how it works and I think this behavior cannot be changed without modifying the source code as @NormalHuman said.
In your example your code is working because you have the "a" variable is defined in the calling scope, but if you execute the function in another situation it could fail. In my opinion a function defined in this way has a defect in its code.
I am using a lot Scilab and I don't see this as a real problem, but I agree with you that this behavior is quite strange and it should not exist.
However, if you are worried of developing incorrectly a function that works well while you are writing the code due to a variable defined in calling scope, the solution for that is to create some unit tests and execute them in a clean interpreter.
Upvotes: 2