I am so sorry for having to ask this question but I'm trying to do a simple if statement that checks if a variable is nil or not.
(defun test (input) (let ((testvar (first input))) (if (not nil testvar) (do this) (do that))))Could anyone explain the proper syntax to me?
13 Answers
Since nil is equivalent to the boolean value false, there is no need to compare to it explicitly.
A simple
(if testvar (...) (...))will do the job. You only need not if you want to check for the opposite, e.g. if you want to check that a variable is not nil:
(if (not testvar) (...) (...))Apart from that, there is also a predicate function called null that you might use. It is basically meant for checking whether a given list is empty, but since the empty list is equivalent to nil, it will work (as the examples on the linked page point out):
(null '()) => T
(null nil) => T
(null t) => NIL
(null 1) => NILAnyway, this basically only moves the problem one layer up ;-)
Do you want to check if the variable is nil or if it is not nil?
For not nil: (if v ... ...)
For nil: (if (not v) ... ...)
There are (in CL) many variations which are all logically the same but may indicate intent better: (if (null v) ... ...) if the same as the second case above but might indicate to the reader that you are looking for `()‘ instead of logical falsity (ie an empty list). And there are plenty of other variations.
jkiiski was right:
Just (if (not testvar) ...). Or put the true branch first and do (if testvar ...)
1