Elisp: Function Parameters (optional, rest)
Optional Parameters
To have optional parameters, add
&optional name1 name2 etc
at the end of parameter list.
- When optional parameter is not given in a function call, its value is
nil. - When an optional parameter has value of
nil, there is no way to know if it is given in function call or omitted.
;; defining a function with 2 optional params named cc and dd (defun ff (aa bb &optional cc dd) "test optional params" (interactive) (message "%s %s %s %s" aa bb cc dd)) ;; call it (ff 1 2) ;; "1 2 nil nil" (ff 1 2 3) ;; "1 2 3 nil" (ff 1 2 3 4) ;; "1 2 3 4"
Rest Parameters (Unspecified Number of Parameters)
To specify unspecified number of parameters, add
&rest name
as the last parameter.
In the function, value of name is a list, or nil if omitted.
You can have both &optional and &rest, in that order.
;; defining a function with rest parameters (defun ff (aa bb &rest cc) "test rest arguments" (message "%s" cc) ; cc is a list ) ;; test (ff "1" "2" "3" "4") ;; ("3" "4")
Example of both optional and rest parameter
(defun xx-test (aa bb &optional cc dd &rest others) "test optional and rest parameters" (message "aa is %s bb is %s cc is %s dd is %s rest is %s" aa bb cc dd others)) ;; test (xx-test 1 2) "aa is 1 bb is 2 cc is nil dd is nil rest is nil" (xx-test 1 2 3) "aa is 1 bb is 2 cc is 3 dd is nil rest is nil" (xx-test 1 2 3 4) "aa is 1 bb is 2 cc is 3 dd is 4 rest is nil" (xx-test 1 2 3 4 5) "aa is 1 bb is 2 cc is 3 dd is 4 rest is (5)" (xx-test 1 2 3 4 5 6) "aa is 1 bb is 2 cc is 3 dd is 4 rest is (5 6)"
No Default Values
- Emacs lisp does not support parameter default value.
- Emacs lisp does not support parameter type checking.
Function Keyword Parameters (Named Parameters)
Elisp, Function
- Elisp: Define Function
- Elisp: Define a Command
- Elisp: Function Parameters (optional, rest)
- Elisp: Function Keyword Parameters (Named Parameters)
- Elisp: Docstring Markup
- Elisp: Lambda Function
- Elisp: Exit Loop or Function (throw, catch)
- Elisp: Apply Function, funcall, identity
- Elisp: Types of Functions