Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Overwrite mata function

    I have some helper functions in a separate script that I `source` from other scripts. It may happen, especially when working interactively, that I source/define the function even though it already exists. I'd like to add a line like mata: capture drop function_name() ahead of the function definition, but there is no capturing in Mata.

    Code:
    mata:
    function f(){
        return(1)
    }
    end
    
    ** do some stuff
    ** remove function or maybe don't
    
    ** later, want to make sure the function is available
    
    <<< What can I insert here? >>>
    
    mata:
    function f(){
        return(1)
    }
    end
    Other ideas besides capture:

    Code:
    mata: mata drop f()
    This fails when the function does not exist.

    Code:
    mata:
    if (findexternal("f()") != NULL){
        mata drop f()
    }
    end
    mata:
    function f(){
        return(1)
    }
    end
    This fails because Mata/Stata is declarative and doesn't like contingent drops ... or something.

    Code:
    mata:
    if (findexternal("f()") == NULL){
        function f(){
            return(1)
        }
    }
    end
    This fails because Mata/Stata is declarative and doesn't like contingent definitions ... or something.

    I got the idea for these latter two from another thread. A 2008 thread seems very closely related, but I can't figure out what is going on in it.
    Last edited by Frank Erickson; 11 Jul 2016, 11:53.

  • #2
    You can "cheat" by using

    Code:
    cap mata mata drop function_name()
    The capture is still in the Stata environment, meaning the code will continue even if there's nothing to drop in mata

    Comment


    • #3
      Yeah, I think that's the ticket. Thanks, Jesse! I just found that with a minute's more googling; turns out it was elsewhere in the last thread I linked.

      Comment

      Working...
      X