You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用AutoLISP实现TEXT/MTEXT属性弹窗?代码报错排查

问题分析与修复

错误「Program ERROR: bad argument type: stringp nil」的核心原因:

  • strcat函数要求所有拼接参数必须是字符串,但你代码中textcolor是整数类型(颜色编号),直接传入会触发类型错误;
  • 若文本对象颜色为「随层」,(cdr (assoc 62 textinfo))会返回nil,同样导致strcat报错;
  • 未考虑部分属性可能缺失的情况,比如特殊文本对象可能没有高度属性(TEXT/MTEXT一般都有,但做兼容更稳妥)。

修正后的代码

(defun c:selecttext()
    (setq textobj (car (entsel "\nSelect text or mtext: ")))
    (if (and textobj (member (cdr (assoc 0 (entget textobj))) '("TEXT" "MTEXT")))
        (progn
            (setq textinfo (entget textobj))
            ;; 处理文本内容,不存在时显示空字符串
            (setq textvalue (if (assoc 1 textinfo) (cdr (assoc 1 textinfo)) ""))
            ;; 处理高度,不存在时显示"未知",转换为带两位小数的字符串
            (setq textheight (if (assoc 40 textinfo) (rtos (cdr (assoc 40 textinfo)) 2 2) "未知"))
            ;; 处理颜色:存在则转字符串,不存在显示"随层"
            (setq textcolor (if (assoc 62 textinfo) (itoa (cdr (assoc 62 textinfo))) "随层"))
            ;; 处理图层,不存在时显示空字符串
            (setq textlayer (if (assoc 8 textinfo) (cdr (assoc 8 textinfo)) ""))
            
            (alert (strcat "Text contents: " textvalue 
                          "\nHeight: " textheight 
                          "\nColor: " textcolor 
                          "\nLayer: " textlayer))
        )
        (alert "Please select a valid text or mtext object.")
    )
    (princ)
)

关键修改点

  • 颜色值用itoa转换为字符串,解决类型不匹配问题;
  • 对每个属性增加存在性判断,用if (assoc ...)检查属性是否存在,不存在时设置默认值(如"随层"、"未知");
  • 高度转换为字符串时,用(rtos ... 2 2)指定十进制格式并保留两位小数,显示更友好;
  • 文本内容和图层属性增加空值处理,避免nil传入strcat触发错误。

内容的提问来源于stack exchange,提问作者codeTester-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:02:57