Virtual Lisp
为了便于 autolisp 的开发调试,autodesk 公司推出了 Virtual Lisp 集成开发环境。在 CAD 命令行输入 vlide 或者 vlisp 即可调出IDE。
CAD 设置
修改支持文件搜索路径,添加自己的脚本文件路径
加载自定义脚本文件
load "脚本名称"
;可以省略lsp后缀
AutoLisp 语法
数据类型
- String
e.g.:
"hello"
- Integers
e.g.:
1 2 3
- Real
e.g.:
1.2
- List
e.g.:
(1 1.2 "hello")
禁止求值
任何使用 () 的地方都会被自动求值,即第一个参数被认为是操作符,后面视为操作数。如果不想被自动求值,例如定义list时:(setq l '(1 2 3))
,可以在括号前加一个单引号。如果此时不加单引号会报错,因为 1
不是一个函数。当列表中元素是变量名时不能这么写,而是应该使用 list 函数求值,才能得到想要的值,例如:
(setq a 100)
(setq b 200)
(setq m (list a b))
变量
变量定义
(setq varname value)
在CAD中查看变量
!varname
不要使用内建函数名称
当名称与内建函数名称冲突时会覆盖内建函数,可以使用名称前缀加
.
符号强制使用内建函数没有单个字符的内建函数名称
a-z
可以随便使用,但要保证他们没有在自动加载的脚本文件中已经使用
NOTE: 变量名称不区分大小写
条件
autolisp 里 nil 是 Falseif
使用格式:
(if BoolExpr DoSomething|(progn DoSomethings) [DoSomething|(progn DoSomethings)] )
示例:
(if (> 10 3) (princ "greater") (princ "less or equal") ) (if (> 10 3) (progn (princ "greater1") (princ "greater2") ) (princ "less or equal") ) (if (> 10 3) (progn (princ "greater1") (princ "greater2") ) (progn (princ "less or equal1") (princ "less or equal2") ) )
cond
使用格式:
(cond (BoolExpr DoSomething|(progn DoSomethings)) (BoolExpr DoSomething|(progn DoSomethings)) (BoolExpr DoSomething|(progn DoSomethings)) ... )
示例:
(setq m 10) (cond ((> m 10) (princ "greater than 10")) ((> m 5) (princ "greater than 5")) ((> m 3) (princ "greater than 3")) )
循环
while
使用格式:
(while BoolExpr DoSomething1 DoSomething2 ... )
示例:
(setq i 1) (while (< i 10) (princ i) (setq i (+ i 1)) )
repeat
使用格式:
(repeat integer DoSomething1 DoSomething2 ... )
示例
(repeat 10 (princ "Hello") )
foreach
使用格式:
(foreach elem mylist DoSomething1withelem DoSomething2withelem ... )
示例
(setq l '(1 2 3)) (foreach i l (princ i) (princ "Hello") )
函数
CAD中带括号执行
使用格式:
(defun funcname(args / localargs)())
示例
(defun hello(msg) (princ msg) )
CAD中不带括号执行
使用格式:
(defun C:funcname(args / localargs)())
示例
(defun C:hello(msg) (princ msg) )
/
参数
这个单独说下,因为它写法比较特殊。它的意思是 / 后面的变量的作用范围只在该函数体。- 示例
(setq m 100) (defun hello() (setq m 99) (princ m) ) (hello)
执行完这个脚本后,我们可以看到m的值变为99了。现在我们让m变量本地化
(setq m 100) (defun hello(/ m) (setq m 99) (princ m) ) (hello)
执行完我们可以看到m的值还是100。
- 示例
返回值
作为函数式编程语言,函数也是表达式,函数体中最后一个表达式的值就是函数的返回值。如果不想函数显示值可以在函数体最后加上(princ)