octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

More subfunction scoping issues.


From: John W. Eaton
Subject: More subfunction scoping issues.
Date: Wed, 4 Apr 2007 14:42:49 -0400

On 30-Mar-2007, David Bateman wrote:

|  What would be needed to fix this issue, as I've
| just been given a large chunk of matlab code that relies on these
| scoping rules?

If your code is not too complex, then you can change it from

  function f ()
    v1 = ...;
    g ()
    ## ... use modified v1 here ...
    function g ()
      v1 = ...;
    end
  end

to

  function f ()
    v1 = ...;
    v1 = g (v1)
    ## ... use modified v1 here ...
  end
  function v1 = g (v1)
    v1 = ...;
  end

Or, if the nested functions don't actually modify the variables they
inherit from the parent, you can omit the output parameters from the
new subfunctions.

If the code you were given is large and has many variables, then this
transformation will be somewhat hard to do unless you understand the
code very well.

If the code you have is complex and has many variables shared between
the parent and nested functions, then I think that as you have to
modify the code you will discover that nested functions are a really
bad idea for a language like the one used by Octave.  The problem is
that you have no way of declaring that a variable is local to a
subfunction and NOT inherited from the parent environment.  That makes
the new scoping rules a code maintenance disaster waiting to happen.
Sure, it is easy to see what might be happening in a simple set of
nested functions with just a few lines of code and variables, but if
you have anything larger than a page or so, then I think you will have
trouble.  It is just too easy to introduce a variable in a nested
function that unintentionally changes the value of a variable in a
parent function.  To be sure that you are not screwing something up,
you need to know the names of all the variables used in the parent
function.  This problem could maybe be solved by introducing the
notion of local variables, but without local variables, I think nested
functions are unusable for anything more than trivially small example
programs.

jwe


reply via email to

[Prev in Thread] Current Thread [Next in Thread]