variables - 如何在 emacs-lisp 中将变量约束为正数?

标签 variables emacs numbers

我有一个可自定义的变量 timer-granularity 用于在每次用户调用类似 (timer-faster) 时增加/减少计时器的周期>(计时器较慢)。但是,如果用户将 timer-granularity 设置为负数,那么调用 (timer-slower) 实际上会使计时器更快!

我想限制此变量的值,以便尝试将其设置为小于某个阈值的值是错误的,例如

(setq timer-granularity 0.3)  ;; okay
(setq timer-granularity -1)  ;; error!

这种行为可以实现吗?

最佳答案

您可以setq anything to anything(无论是否合理),但您当然可以将验证添加到customize 界面。例如:

(define-widget 'integer-positive 'integer
  "Value must be a positive integer."
  :validate (lambda (widget)
              (let ((value (widget-value widget)))
                (when (or (not (integerp value)) (<= value 0))
                  (widget-put widget :error "Must be a positive integer")
                  widget))))

(defcustom foo 1 "Positive int"
  :type 'integer-positive)

您可以向 timer-fastertimer-slower 添加错误处理——但在这种情况下,我想我只是相信用户知道它们是什么如果他们在 elisp 中设置值,则执行此操作。


为了完整性:Emacs 26.1 确实引入了 add-variable-watcher 可以用来捕获“无效的”setq,但老实说我认为这不合理将其用于如此微不足道的目的。 customize UI 是断言此类内容的正确位置。

关于variables - 如何在 emacs-lisp 中将变量约束为正数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358421/

相关文章:

java - Java 中字节不显示加法结果

python - 在 Python 3 中正确使用全局变量

javascript - 用空格混淆变量名

perl - 如何在 Perl 中将变量打印到文件中?

emacs - 从命令行运行emacs并处理锁定的文件

java - BigInteger.ValueOf() 返回缓存的对象?

java - 小数java

emacs - 如何在 emacs 和 leiningen 中使用 repl

ubuntu - 终结器中的 Emacs goto-line 不起作用

asp.net-mvc - 使用 asp.net mvc 用逗号分隔数字