So far we have saved a series of AutoLISP expressions in a *.LSP file. Every time we load the *.LSP file, all expressions contained within it are executed. What would be more useful is to be able to create new AutoLISP functions and use them as many times as desired without loading each time. Such user-defined AutoLISP functions are created using the (defun) function.
Explanation: the (defun) function
(defun name ( [arguments] )
[the AutoLISP routine(s)…]
The name is a symbol that becomes the name of the function. The arguments is a list of all required arguments. Typically this is a list of all symbols used by the routine. It can be an empty list.
- The rest of the information is the definition of the new function. Example
(defun DegreesToRadians (DEGREE)
(* DEGREE (/ PI 180.0))
The first line uses the (defun) function to create a user-defined function called DegreesToRadians and declares that the new function will require one argument that will be referred to as DEGREE during the evaluation of the function.
The second line describes what is going to happen whenever the (DegreesToRadians) function is used. It will take the argument – DEGREE – and multiply it by whatever is returned after dividing PI by 180. (This is the formula for converting degrees to radians, which will be very useful later on.)
The last line closes the (defun) function.
- Think of this as a massive (setq) function, storing all the expressions listed within the expression under the symbol name <name>.
- The (defun) function returns the name of the function.
- The new function can now be used as all other pre-defined functions: (function argument1 … argumentn). All expressions within the function are then evaluated, and the function will return the value of the last expression.
- If the user-defined function requires no arguments, simply provide an empty list. (defun STUFF ( )…)
- Do not use the name of a pre-defined function as your function name or the pre-defined function will become inaccessible.
- The name of the function is not case-sensitive.
In this practice we will define two AutoLISP functions: DegreesToRadians and RadiansToDegrees. We will need these later in the class. You will also want them for your work since all angles are measured in radians by AutoLISP. Estimated time for completion:
1. Start a new file in Visual LISP and name it TRANSLATION.LSP
2. Add the following code to it:
(defun DegreesToRadians (DEGREES)
(* DEGREES (/ PI 180.0))
(defun RadiansToDegrees (RADIANS)
(* 180.0 ( / RADIANS PI)
3. Once you have created the file, load it and try several different angles.
- A complete solution to this exercise is on your class disk as TRANSLATION-A.LSP.