Saturday, July 12, 2014

Repetition Functions

Repetition Functions


Now we come to the repetition functions. They are very important. Repetition functions are often used in AutoLISP programs.


Here they are:


WHILE Function


(while (<test> <expression> …)


This function performs a test at the beginning. If the test gives nil, then the expressions are evaluated.


Example:


(defun c:numbr (/ nr)
(setq nr 1)
(while (<= nr 5)
(princ "\nNumber: ")
(princ nr)
(setq nr (1+ nr))
)
(princ)
)
(c:numbr)


At the start of the AutoLISP program the variable NR is given the value 1. The value of the variable is tested at the beginning of the WHILE function.


As long as the value is less or equal to five, then the expressions in the WHILE function are evaluated.


This is given back by the AutoLISP program:


Number: 1
Number: 2
Number: 3
Number: 4
Number: 5


Repeat Function


(repeat <number> <expression> …)


Now the number of repetitions can be specified.


Example:


(princ "\n")
(defun c:repfc ()
(repeat 4
(princ "-")
)
(princ)
)
(c:repfc)


This is given back by the AutoLISP program:


----


Foreach Function


(foreach <name> <list> <expression> …)


This function goes through a list and gives every element of the list a name. The expression is performed for every name.


Example:


(foreach n (list 1 2 3) (* n 2))


The AutoLISP line gives back 6. The number 3 is multiplied with 2.


Exercise:


We have been talking about predicates, test functions and repetition functions. Here is an exercise to use what has been taught.


Write the SLINE AutoLISP program. The following prompts will show up:


Command: SLINE
Color/Linetype/<first point>: C
Color: 1
Color/Linetype/<first point>: L
Linetype: Hidden
Color/Linetype/<first point>: 100,100
Close/<next point>: 300,300
Close/<next point>: C
Command: