1

I wanted to check that char is a digit by comparing its code with codes of 0 and 9, presuming that the digits codes are contiguous in code table:

(let ((char ?\e))
  (if (and (>= char ?\0) (<= char ?\9))
      (message "aaa")
    (message "bbb")))

But it doesn't work: this code returns "aaa", even though e is not a digit.

What is wrong?

user4035
  • 1,059
  • 13
  • 24

1 Answers1

8

Remove the backslashes before e, 0 and 9.

(let ((char ?e))
  (if (<= ?0 char ?9)
      (message "It's a digit")
    (message "It's not a digit")))

With the backslashes:

  • \e is the escape char - ASCII 27.
  • \0 is the null char - ASCII 0.
  • \9 isn't special, so it's the same as 9 - ASCII 57.
  • 27 is >= 0 and <= 57.
Phil Hudson
  • 1,741
  • 10
  • 13
aadcg
  • 1,248
  • 6
  • 13
  • "\0 is null char ascii 0" - how to use ASCII 48 = "0" instead of ASCII 0? – user4035 Nov 17 '21 at 11:35
  • 4
    This answer tells and shows you exactly how to do that. – phils Nov 17 '21 at 12:03
  • 3
    See also C-h i g (elisp)Basic Char Syntax and (elisp)General Escape Syntax. Note that ?\0 is being read as an octal value which is also why ?\9 is not treated the same way (as only the digits 0-7 are valid in octal). You can specify octal character codes up to ?\777 with this syntax. – phils Nov 17 '21 at 13:29