可選引數

可以使用 &OPTIONAL 關鍵字在必需引數之後指定可選引數。它後面可能有多個可選引數。

(defun foobar (x y &optional z)
  (format t "X (~s) and Y (~s) are required.~@
             Z (~s) is optional.~%"
          x y z))

(foobar 10 20)
; X (10) and Y (20) are required.
; Z (NIL) is optional.
;=> NIL
(foobar 10 20 30)
; X (10) and Y (20) are required.
; Z (30) is optional.
;=> NIL

預設值

通過使用列表指定引數,可以為可選引數指定預設值; 第二個值是預設值。只有在給出引數時才會評估預設值表單,因此它可以用於副作用,例如發出錯誤訊號。

(defun foobar (x y &optional (z "Default"))
  (format t "X (~s) and Y (~s) are required.~@
             Z (~s) is optional.~%"
          x y z))

(foobar 10 20)
; X (10) and Y (20) are required.
; Z ("Default") is optional.
;=> NIL
(foobar 10 20 30)
; X (10) and Y (20) are required.
; Z (30) is optional.
;=> NIL

檢查是否給出了可選引數

可以在預設值之後將第三個成員新增到列表中; 變數名稱,如果給出了引數,則為 true;如果未給出,則為 NIL(並且使用預設值)。

(defun foobar (x y &optional (z "Default" zp))
  (format t "X (~s) and Y (~s) are required.~@
             Z (~s) is optional. It ~:[wasn't~;was~] given.~%"
          x y z zp))

(foobar 10 20)
; X (10) and Y (20) are required.
; Z ("Default") is optional. It wasn't given.
;=> NIL
(foobar 10 20 30)
; X (10) and Y (20) are required.
; Z (30) is optional. It was given.
;=> NIL