no function definition: RETURN

39 Views Asked by At

I want to use keyword "return" to return value for a function but I got a runtime error enter image description here

I can only successfully return value as below. However, the function will not "end directly" after if condition == true at line #3. Could someone give a hint how to use "return" keyword correctly? enter image description here

2

There are 2 best solutions below

3
Lee Mac On BEST ANSWER

AutoLISP does not have a return function.

You would need to structure your code such that the remainder of the code is evaluated as part of the else argument for the if statement, e.g.:

(defun findLastDigitIndex ( str startIdx / char )
    (setq char (substr str startIdx 1))
    (if (or (< (ascii char) 48) (> (ascii char) 57))
        nil
        (progn
            ;; do stuff
        )
    )
)

But I might write the function as follows:

(defun findLastDigitIndex ( str startIdx / dif )
    (setq str (substr str startIdx)
          dif (- (strlen str) (length (vl-member-if-not '(lambda ( a ) (< 47 a 58)) (vl-string->list str))))
    )
    (if (< 0 dif) (+ startIdx dif -1))
)
2
Wu Yuan Chun On

It's a good convention to always put "return value" in the very end of function. In fact, it's a requirement.

Indeed in the code below, that first return value of nil will be overwritten by the logic that follows after it.

(defun test()
   (if someSimpleCheck
      nil
   )
   ;; do many logic and get retValue
   retValue
)

In Autolisp, we cannot leave a function in the middle. It will always run its course through all of the code. So it must instead be

(defun test()
   (if someSimpleCheck
      nil                     ; EITHER this
      (progn
         ;; do many logic and get retValue
         retValue             ; OR this
      )))

Here nil will be returned is someSimpleCheck is not nil, and retValue will be returned if someSimpleCheck is indeed nil.