Skip to content

Option sets

Ken Haase edited this page Feb 25, 2021 · 1 revision

KNO provides a simple and lightweight system for passing sets of options to functions. Most of Kno's native functions and modules take both positional arguments and option set arguments.

Option sets are either tables (usually a slotmap or schemap) or a pair of a table with another option object. Options are usually created by adding new named options to an existing options object. This is usually done by creating a new table from the named options and then making a pair of the new table and a current option set.

The function GETOPT (or it's C API equivalent) takes one of these option objects, an option name (a symbol), and returns the first specification of of the named option in the option set.

For example,

(define default-opts #[height 1024 width 512])
#|kno>| (getopt default-opts 'height)
1024
;; `GETOPT` takes a default value as an extra optional argument.
#|kno>| (getopt default-opts 'weight 200)
200
;; The default default value (got that?) is `#f`
#|kno>| (getopt default-opts 'weight)
#f
;; We can just combine options with `CONS`
(define mod-opts (cons #[width 1024 weigh 17] #[height 1024 width 512]))
#|kno>| (getopt mod-opts 'height)
1024
#|kno>| (getopt mod-opts 'width)
1024
#|kno>| (getopt mod-opts 'weight)
17
#|kno>| (getopt mod-opts 'weight 200)
17

The function TESTOPT tests an optional set for a particular option.

#|kno>| (testopt mod-opts 'weight 200)
#f
#|kno>| (testopt mod-opts 'weight 17)
#t
;;; With no value argument, `TESTOPT` returns #t if the option is set
;;; in the option set at all.
#|kno>| (testopt mod-opts 'weight)
#t
#|kno>| (testopt mod-opts 'age)
#f

While option sets can be constructed easily with CONS, a few special functions exist for extending option sets. OPTS+ takes an option set and adds options based on its alternating name/value arguments, e.g.

(define more-opts (opts+ default-opts 'width 64 'weight 7)
#|kno>| (getopt more-opts 'age)
#f
#|kno>| (getopt more-opts 'width)
64
Clone this wiki locally