Search code examples
lispautocad-pluginautolisp

In AutoLISP is it possible to get function name in function body?


In specified conditions I want to print name of fuction in this function. but I don't know how to get it. In C++ I can use preprocessor macro __FUNCTION__. I something simmilar in AutoLISP?


Solution

  • This is definitely possible. Let's look at two situations:

    1) You're writing the function.

    This should be easy, just define a variable that has the same name as the function and you're good to go. (As discussed in the comments above.)

    You could even use something more descriptive than the actual name of the function. (defun af () ...) could be called "Awesome Function" instead of "af".

    I would also recommend using standard constant value formatting: Capital letters with underscores to separate words. (setq FUNCTION_NAME "AwesomeFunction"). (This is just like PI which is set for you and you shouldn't change it - it's a constant.)

    2) You're calling a function that you might not know the name of until the code runs.

    Some examples of this:

    (apply someFunctionInThisVariable '(1 2 3))
    
    (mapcar 'printTheNameOfAFunction '(+ setq 1+ foreach lambda))
    
    (eval 'anotherFunctionInAVariable)
    

    To print the name of a function stored in a variable - like this (setq function 'myFunction) - you need to use the (vl-princ-to-string) function.

    (vl-princ-to-string function)   ;; Returns "MYFUNCTION"
    (strcase (vl-princ-to-string function) T)   ;; Returns "myfunction"
    
    (princ
       (strcase 
          (vl-princ-to-string function)
          T
       )
    )            ;; Command line reads: myfunction
    

    The (vl-princ-to-string) function can be used on any type that can be printed and will always return a string. It's great if you don't know whether you have a number or a word, etc.

    Hope that helps!

    P.S. I first used this technique when I was writing a testing function. Send it a function and an expected value and it would test to see if it worked as expected - including printing the function's name out as part of a string. Very useful if you have the time to setup the tests.