benhubel 发表于 2022-7-5 15:50:06

定义生成的变量loc

我一直在尝试通过代码生成变量,而不是手动定义它们。问题是,当程序创建它们时,它们被定义为全局变量。有没有办法将它们生成为局部变量?
 
下面是我为测试它而编写的示例代码。
 
;ListToVariables creates variables named testvar0, testvar1, testvar2, etc.
;Each newly created variable contains the contents of the correlated slot from testlist.
(defun c:test ( / testlist )
(setq testlist (list "aaa" "bbb" "ccc" "ddd" "eee"))
(ListToVariables testlist)
)

(defun ListToVariables ( listname / i )
(setq i 0)
(repeat (length listname)
        (set (read (strcat "testvar" (rtos i 2 0))) (nth i listname))
        (setq i (1+ i))
)
(princ)
)

David Bethel 发表于 2022-7-5 16:23:48

你可以,但这是RPIA
 
最好是对这些类型使用标准名称约定,这些类型将仅用于该会话
 
我使用前缀gv_表示全局变量,并设置为可重用,tv_表示临时变量
 
-大卫

benhubel 发表于 2022-7-5 16:46:40

 
这很有道理,而且听起来我可能不得不走这条路。出于好奇,我仍然对如何生成局部变量感兴趣。如果有人有任何例子,或者有任何描述它的文档的链接,我很乐意去看看。我现在能想到的唯一方法是把它写成一个中间程序,它编写自己的函数,在本地声明变量。

Grrr 发表于 2022-7-5 17:02:17

大概
 

; (ListToVariables "hello" '(44 55 88))
(defun ListToVariables ( pref L / varnm i r )
(setq i 0)
(foreach x L
   (set (read (setq varnm (strcat pref (itoa (setq i (1+ i)))))) x)
   (setq r (cons varnm r))
)
(reverse r)
)
 

(ListToVariables "hello" '(44 55 88)) >> ("hello1" "hello2" "hello3")
hello1 >> 44
hello2 >> 55
hello3 >> 88
hello4 >> nil
页: [1]
查看完整版本: 定义生成的变量loc