Here's an example for how to combine Options
, OptionsPattern
, and OptionValue
:
First, define the available options for f
and their default values:
Options[f] = {"TheMainOption" -> 0,
"SomeOtherOption" -> 7,
"TheLetter" -> "A"};
Then, define the function f
(here: make a list of all option values, in a particular order that is independent of the order in which the user specifies the options in the function call):
f[OptionsPattern[]] := {OptionValue["TheMainOption"],
OptionValue["SomeOtherOption"],
OptionValue["TheLetter"]}
Note that by default, OptionsPattern[]
looks up the available options and defaults from the associated definition of Options[f]
.
Tests: the options can be given in any order, and default values are provided in the definition of Options[f]
:
f[]
(* {0, 7, "A"} *)
f["TheLetter" -> "Z"]
(* {0, 7, "Z"} *)
f["TheLetter" -> "N", "SomeOtherOption" -> -2]
(* {0, -2, "N"} *)
Remind me what the options and defaults were for f
?
Options[f]
(* {"TheMainOption" -> 0, "SomeOtherOption" -> 7, "TheLetter" -> "A"} *)
f["WhatImGetting" -> 5, "TheMainThing" -> 8, "SomethingElse" -> 77]
as usual with options. $\endgroup$ – Roman Jun 27 '19 at 17:42f
to work with associations too. $\endgroup$ – Kuba♦ Jun 28 '19 at 8:31