;Evaluate math expressions in AutoCAD texts
;V.Michl, www.cadforum.cz - www.arkance-systems.cz

(vl-load-com)

(defun C:EvalText ( / n s e ed i c modt)

(defun evalVBS (VBcommand / f scr cmd tmp res)
 (if (and VBcommand (= (type VBcommand) 'STR) )
  (progn
  (setq f (open (setq tmp (vl-filename-mktemp "evaltext.vbs")) "w"))
  (setq cmd (strcat "
Dim result
Set wshshell = CreateObject(\"wscript.shell\")
" VBcommand "
wshshell.RegWrite \"HKCU\\Software\\Arkance Systems\\VBSkey\\evalVBS\", result, \"REG_SZ\"
Set wshshell = Nothing
"
   ))
  (write-line cmd f)
  (close f)
  (if (setq scr (vlax-create-object "wscript.shell"))(progn
   (if (not (vl-catch-all-error-p
         (vl-catch-all-apply 'vlax-invoke-method (list scr 'run (strcat "cscript " tmp) 0 :vlax-true)) ; 0=hidden, wait
       ))
       (setq res (vl-registry-read "HKEY_CURRENT_USER\\Software\\Arkance Systems\\VBSkey" "evalVBS"))
   )
   (vl-registry-delete "HKEY_CURRENT_USER\\Software\\Arkance Systems\\VBSkey" "evalVBS")
   (vlax-release-object scr)
  )) ; if OK
  res
  ) ; progn, else:
  nil
  ) ; if string
) ; defun

  (princ "\nSelect expression texts <ENTER for immediate> ")
  (if (setq n 0  s (ssget '((0 . "*TEXT") (1 . "*#*"))))(progn
    (initget "Yes No")
	(setq modt (getkword "\nWrite results back to texts? [Yes/No] <No>: "))
    (repeat (setq i (sslength s))
      (setq c (cdr (assoc 1 (setq ed (entget (setq e (ssname s (setq i (1- i)))))))))
      (setq n (evalVBS (strcat "result = " c)))
	  (if (> n "")(progn
       (princ (strcat "\nResult: " c " = " (vl-princ-to-string n)))
	   (if (= modt "Yes")(progn
	    (setq ed (subst (cons 1 (vl-princ-to-string n))(assoc 1 ed) ed))
	    (entmod ed)
	    (entupd e)
	   )); modt
	  ) ; else
	   (princ (strcat "\nFail: " c " | " n))
	  )
	) ; rep
   ) ; else no text:
   (progn
    (setq c (getstring "\nType the expression: " T))
    (setq n (evalVBS (strcat "result = " c)))
	(if (> n "")
      (princ (strcat "\nResult: " c " = " (vl-princ-to-string n)))
	  (princ (strcat "\nFail: " c " | " n))
	)
   )
  ) ;if
  (princ)
)

(princ "\nEvalText command loaded. Type EVALTEXT to invoke.")
(princ)


