Skip to content

Commit e184047

Browse files
committed
Add multi-parameter info
1 parent 1634a31 commit e184047

File tree

1 file changed

+45
-11
lines changed

1 file changed

+45
-11
lines changed

book/custom_commands.md

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -206,27 +206,61 @@ def "custom command" [] {
206206

207207
## Parameters
208208

209+
### Multiple parameters
210+
211+
In the `def` command, the parameters are defined in a [`list`](./types_of_data.md#lists). This means that multiple parameters can be separated with spaces, commas, or line-breaks.
212+
213+
For example, here's a version of `greet` that accepts two names. Any of these three definitions will work:
214+
215+
```nu
216+
# Spaces
217+
def greet [name1 name2] {
218+
$"Hello, ($name1) and ($name2)!"
219+
}
220+
221+
# Commas
222+
def greet [name1, name2] {
223+
$"Hello, ($name1) and ($name2)!"
224+
}
225+
226+
# Linebreaks
227+
def greet [
228+
name1
229+
name2
230+
] {
231+
$"Hello, ($name1) and ($name2)!"
232+
}
233+
```
234+
209235
### Required positional parameters
210236

211-
The basic argument definitions used above are _positional_. The first parameter passed into the `greet` command above is assigned to the first `name` parameter.
237+
The basic argument definitions used above are _positional_. The first argument passed into the `greet` command above is assigned to the `name1` parameter (and, as mentioned above, the `$name1` variable). The second argument becomes the `name2` parameter and the `$name2` variable.
212238

213-
By default, positional parameters are required. If a positional parameter is not provided, we will encounter an error. Using our basic `greet` command:
239+
By default, positional parameters are _required_. Using our previous definition of `greet` with two required, positional parameters:
214240

215241
```nu
216-
def greet [name] {
242+
def greet [name1, name2] {
217243
$"Hello, ($name)!"
218244
}
219245
220-
greet
221-
# => × Missing required positional argument.
222-
# => ╭─[entry #23:1:1]
223-
# => 1 │ greet
224-
# => · ▲
225-
# => · ╰── missing name
226-
# => ╰────
227-
# => help: Usage: greet <name>
246+
greet Wei Mei
247+
# => Hello, Wei and Mei!
248+
249+
greet Wei
250+
# => Error: nu::parser::missing_positional
251+
# =>
252+
# =>
253+
# => × Missing required positional argument.
254+
# => ╭─[entry #10:1:10]
255+
# => 1 │ greet Mei
256+
# => ╰────
257+
# => help: Usage: greet <name1> <name2> . Use `--help` for more information.
228258
```
229259

260+
::: tip
261+
Try typing a third name after this version of `greet`. Notice that the parser automatically detects the error and highlights the third argument as an error even before execution.
262+
:::
263+
230264
### Optional Positional Parameters
231265

232266
We can define a positional parameter as optional by putting a question mark (`?`) after its name. For example:

0 commit comments

Comments
 (0)