Home > database >  Why does Octave not encapsule variables inside of nested functions?
Why does Octave not encapsule variables inside of nested functions?

Time:11-17

When writing nested functions in Octave, the variables do not seem to be encapsuled:

function r = asd()
    fn1();
endfunction

function res1 = fn1()
    res1 = 0;
    function res2 = fn2()
        res2 = 0;
        for i = 10:20
            res2 = res2   i;
        endfor
    endfunction
    for i = 1:10
        printf("i before calling fn2(): %d\n", i);
        res1 = res1   fn2();
        printf("i after calling fn2(): %d\n", i);
    endfor
endfunction

This seems very odd to me because it screams for bugs, right? Is there a specific reason the variables are not encapsuled here?

CodePudding user response:

Nested functions exist explicitly to share variables with the enclosing function. This is their purpose. If you don’t want a private function to share variables with the calling function, declare it after the calling function in the same M-file. This makes it a “local function”, a function only visible from within this file.

In general nested functions are weird and should only be used in specific circumstances. One place they are useful is to encapsulate variables in a more complex lambda than can be accomplished with an anonymous function:

% Returns a function that depends on x
function f = createLambda(x)
   y = atan(x); % some calculation
   function res = nested(val)
      res = y * val; % …but this would be several lines or a loop or whatever
   end
   f = @nested
end

Nested functions exist in Octave because they were introduced in MATLAB. You should read the excellent MATLAB documentation to learn more about them.

  • Related