Problem with scoping rules of sub-functions used as function handles in 3.0.x and 3.1.x

John W. Eaton jwe at bevo.che.wisc.edu
Thu Jun 12 12:04:18 CDT 2008


On 12-Jun-2008, David Bateman wrote:

| Consider the piece of code
| 
| function [g,h] = test_fhandle ()
|   g = @(x) func2 (x);
|   h = func1 ();
| end
| function h = func1 ()
|   h = @(x) func2 (x);
| end
| function y = func2 (x)
|   y = x;
| end
| 
| and then run "[g, h] = test_fhandle". Under matlab g(1) and h(1) both
| return the function evaluation. However in 3.0.1 "h(1)" fails as "func2"
| is not in the scope of the handle even though clearly it is in the scope
| of func1 above where the handle is defined. Something similar happens in
| 3.1.x though "func2" doesn't appear to be defined in either of the
| returned function handles.. I have some code that would be simplified if
| this worked correctly.

I'm not sure precisely how to fix this problem as I'm having trouble
deciding what scope information to store, where to store it, and
exactly where it should be used.

Can you modify your code to be

  function [g,h] = test_fhandle ()
    g = @func2;
    h = func1 ();
  end
  function h = func1 ()
    h = @func2;
  end
  function y = func2 (x)
    y = x;
  end

instead?  I think that works with the current sources.

BTW, in Matlab, an anonymous function or function handle created this
way apparently carries with it the name of the .m file wher it is
defined so that if the .m file changes, that change is reflected in
calls through the handle.  In Octave, we currently store some scope
information and duplicate the function body so that if the function is
cleared or the .m file is changed or deleted, the call to the handle
is unchanged.

BTW, the method used by Matlab is patented, apparently including the
use of the @ symbol to create function handles that behave this way
(US Patent #6,857,118).

Whatever happens, I don't expect that this problem will be fixed in 3.0.x.

jwe


More information about the Bug-octave mailing list